另客网go项目公用的代码库

routergroup.go 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "net/http"
  7. "path"
  8. "regexp"
  9. "strings"
  10. )
  11. type IRouter interface {
  12. IRoutes
  13. Group(string, ...HandlerFunc) *RouterGroup
  14. }
  15. type IRoutes interface {
  16. Use(...HandlerFunc) IRoutes
  17. Handle(string, string, ...HandlerFunc) IRoutes
  18. Any(string, ...HandlerFunc) IRoutes
  19. GET(string, ...HandlerFunc) IRoutes
  20. POST(string, ...HandlerFunc) IRoutes
  21. DELETE(string, ...HandlerFunc) IRoutes
  22. PATCH(string, ...HandlerFunc) IRoutes
  23. PUT(string, ...HandlerFunc) IRoutes
  24. OPTIONS(string, ...HandlerFunc) IRoutes
  25. HEAD(string, ...HandlerFunc) IRoutes
  26. StaticFile(string, string) IRoutes
  27. Static(string, string) IRoutes
  28. StaticFS(string, http.FileSystem) IRoutes
  29. }
  30. // RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix
  31. // and an array of handlers (middleware).
  32. type RouterGroup struct {
  33. Handlers HandlersChain
  34. basePath string
  35. engine *Engine
  36. root bool
  37. }
  38. var _ IRouter = &RouterGroup{}
  39. // Use adds middleware to the group, see example code in github.
  40. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {
  41. group.Handlers = append(group.Handlers, middleware...)
  42. return group.returnObj()
  43. }
  44. // Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
  45. // For example, all the routes that use a common middlware for authorization could be grouped.
  46. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
  47. return &RouterGroup{
  48. Handlers: group.combineHandlers(handlers),
  49. basePath: group.calculateAbsolutePath(relativePath),
  50. engine: group.engine,
  51. }
  52. }
  53. func (group *RouterGroup) BasePath() string {
  54. return group.basePath
  55. }
  56. func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
  57. absolutePath := group.calculateAbsolutePath(relativePath)
  58. handlers = group.combineHandlers(handlers)
  59. group.engine.addRoute(httpMethod, absolutePath, handlers)
  60. return group.returnObj()
  61. }
  62. // Handle registers a new request handle and middleware with the given path and method.
  63. // The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.
  64. // See the example code in github.
  65. //
  66. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  67. // functions can be used.
  68. //
  69. // This function is intended for bulk loading and to allow the usage of less
  70. // frequently used, non-standardized or custom methods (e.g. for internal
  71. // communication with a proxy).
  72. func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
  73. if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil {
  74. panic("http method " + httpMethod + " is not valid")
  75. }
  76. return group.handle(httpMethod, relativePath, handlers)
  77. }
  78. // POST is a shortcut for router.Handle("POST", path, handle).
  79. func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {
  80. return group.handle("POST", relativePath, handlers)
  81. }
  82. // GET is a shortcut for router.Handle("GET", path, handle).
  83. func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
  84. return group.handle("GET", relativePath, handlers)
  85. }
  86. // DELETE is a shortcut for router.Handle("DELETE", path, handle).
  87. func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {
  88. return group.handle("DELETE", relativePath, handlers)
  89. }
  90. // PATCH is a shortcut for router.Handle("PATCH", path, handle).
  91. func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {
  92. return group.handle("PATCH", relativePath, handlers)
  93. }
  94. // PUT is a shortcut for router.Handle("PUT", path, handle).
  95. func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {
  96. return group.handle("PUT", relativePath, handlers)
  97. }
  98. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).
  99. func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {
  100. return group.handle("OPTIONS", relativePath, handlers)
  101. }
  102. // HEAD is a shortcut for router.Handle("HEAD", path, handle).
  103. func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {
  104. return group.handle("HEAD", relativePath, handlers)
  105. }
  106. // Any registers a route that matches all the HTTP methods.
  107. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
  108. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
  109. group.handle("GET", relativePath, handlers)
  110. group.handle("POST", relativePath, handlers)
  111. group.handle("PUT", relativePath, handlers)
  112. group.handle("PATCH", relativePath, handlers)
  113. group.handle("HEAD", relativePath, handlers)
  114. group.handle("OPTIONS", relativePath, handlers)
  115. group.handle("DELETE", relativePath, handlers)
  116. group.handle("CONNECT", relativePath, handlers)
  117. group.handle("TRACE", relativePath, handlers)
  118. return group.returnObj()
  119. }
  120. // StaticFile registers a single route in order to serve a single file of the local filesystem.
  121. // router.StaticFile("favicon.ico", "./resources/favicon.ico")
  122. func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {
  123. if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
  124. panic("URL parameters can not be used when serving a static file")
  125. }
  126. handler := func(c *Context) {
  127. c.File(filepath)
  128. }
  129. group.GET(relativePath, handler)
  130. group.HEAD(relativePath, handler)
  131. return group.returnObj()
  132. }
  133. // Static serves files from the given file system root.
  134. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  135. // of the Router's NotFound handler.
  136. // To use the operating system's file system implementation,
  137. // use :
  138. // router.Static("/static", "/var/www")
  139. func (group *RouterGroup) Static(relativePath, root string) IRoutes {
  140. return group.StaticFS(relativePath, Dir(root, false))
  141. }
  142. // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
  143. // Gin by default user: gin.Dir()
  144. func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {
  145. if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
  146. panic("URL parameters can not be used when serving a static folder")
  147. }
  148. handler := group.createStaticHandler(relativePath, fs)
  149. urlPattern := path.Join(relativePath, "/*filepath")
  150. // Register GET and HEAD handlers
  151. group.GET(urlPattern, handler)
  152. group.HEAD(urlPattern, handler)
  153. return group.returnObj()
  154. }
  155. func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {
  156. absolutePath := group.calculateAbsolutePath(relativePath)
  157. fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
  158. _, nolisting := fs.(*onlyfilesFS)
  159. return func(c *Context) {
  160. if nolisting {
  161. c.Writer.WriteHeader(http.StatusNotFound)
  162. }
  163. fileServer.ServeHTTP(c.Writer, c.Request)
  164. }
  165. }
  166. func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {
  167. finalSize := len(group.Handlers) + len(handlers)
  168. if finalSize >= int(abortIndex) {
  169. panic("too many handlers")
  170. }
  171. mergedHandlers := make(HandlersChain, finalSize)
  172. copy(mergedHandlers, group.Handlers)
  173. copy(mergedHandlers[len(group.Handlers):], handlers)
  174. return mergedHandlers
  175. }
  176. func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {
  177. return joinPaths(group.basePath, relativePath)
  178. }
  179. func (group *RouterGroup) returnObj() IRoutes {
  180. if group.root {
  181. return group.engine
  182. }
  183. return group
  184. }