routergroup.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. var (
  12. // regEnLetter matches english letters for http method name
  13. regEnLetter = regexp.MustCompile("^[A-Z]+$")
  14. // anyMethods for RouterGroup Any method
  15. anyMethods = []string{
  16. http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch,
  17. http.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect,
  18. http.MethodTrace,
  19. }
  20. )
  21. // IRouter defines all router handle interface includes single and group router.
  22. type IRouter interface {
  23. IRoutes
  24. Group(string, ...HandlerFunc) *RouterGroup
  25. }
  26. // IRoutes defines all router handle interface.
  27. type IRoutes interface {
  28. Use(...HandlerFunc) IRoutes
  29. Handle(string, string, ...HandlerFunc) IRoutes
  30. Any(string, ...HandlerFunc) IRoutes
  31. GET(string, ...HandlerFunc) IRoutes
  32. POST(string, ...HandlerFunc) IRoutes
  33. DELETE(string, ...HandlerFunc) IRoutes
  34. PATCH(string, ...HandlerFunc) IRoutes
  35. PUT(string, ...HandlerFunc) IRoutes
  36. OPTIONS(string, ...HandlerFunc) IRoutes
  37. HEAD(string, ...HandlerFunc) IRoutes
  38. StaticFile(string, string) IRoutes
  39. StaticFileFS(string, string, http.FileSystem) IRoutes
  40. Static(string, string) IRoutes
  41. StaticFS(string, http.FileSystem) IRoutes
  42. }
  43. // RouterGroup is used internally to configure router, a RouterGroup is associated with
  44. // a prefix and an array of handlers (middleware).
  45. type RouterGroup struct {
  46. Handlers HandlersChain
  47. basePath string
  48. engine *Engine
  49. root bool
  50. }
  51. var _ IRouter = &RouterGroup{}
  52. // Use adds middleware to the group, see example code in GitHub.
  53. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {
  54. group.Handlers = append(group.Handlers, middleware...)
  55. return group.returnObj()
  56. }
  57. // Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix.
  58. // For example, all the routes that use a common middleware for authorization could be grouped.
  59. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
  60. return &RouterGroup{
  61. Handlers: group.combineHandlers(handlers),
  62. basePath: group.calculateAbsolutePath(relativePath),
  63. engine: group.engine,
  64. }
  65. }
  66. // BasePath returns the base path of router group.
  67. // For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".
  68. func (group *RouterGroup) BasePath() string {
  69. return group.basePath
  70. }
  71. func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
  72. absolutePath := group.calculateAbsolutePath(relativePath)
  73. handlers = group.combineHandlers(handlers)
  74. group.engine.addRoute(httpMethod, absolutePath, handlers)
  75. return group.returnObj()
  76. }
  77. // Handle registers a new request handle and middleware with the given path and method.
  78. // The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.
  79. // See the example code in GitHub.
  80. //
  81. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  82. // functions can be used.
  83. //
  84. // This function is intended for bulk loading and to allow the usage of less
  85. // frequently used, non-standardized or custom methods (e.g. for internal
  86. // communication with a proxy).
  87. func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
  88. if matched := regEnLetter.MatchString(httpMethod); !matched {
  89. panic("http method " + httpMethod + " is not valid")
  90. }
  91. return group.handle(httpMethod, relativePath, handlers)
  92. }
  93. // POST is a shortcut for router.Handle("POST", path, handle).
  94. func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {
  95. return group.handle(http.MethodPost, relativePath, handlers)
  96. }
  97. // GET is a shortcut for router.Handle("GET", path, handle).
  98. func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
  99. return group.handle(http.MethodGet, relativePath, handlers)
  100. }
  101. // DELETE is a shortcut for router.Handle("DELETE", path, handle).
  102. func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {
  103. return group.handle(http.MethodDelete, relativePath, handlers)
  104. }
  105. // PATCH is a shortcut for router.Handle("PATCH", path, handle).
  106. func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {
  107. return group.handle(http.MethodPatch, relativePath, handlers)
  108. }
  109. // PUT is a shortcut for router.Handle("PUT", path, handle).
  110. func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {
  111. return group.handle(http.MethodPut, relativePath, handlers)
  112. }
  113. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).
  114. func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {
  115. return group.handle(http.MethodOptions, relativePath, handlers)
  116. }
  117. // HEAD is a shortcut for router.Handle("HEAD", path, handle).
  118. func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {
  119. return group.handle(http.MethodHead, relativePath, handlers)
  120. }
  121. // Any registers a route that matches all the HTTP methods.
  122. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
  123. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
  124. for _, method := range anyMethods {
  125. group.handle(method, relativePath, handlers)
  126. }
  127. return group.returnObj()
  128. }
  129. // StaticFile registers a single route in order to serve a single file of the local filesystem.
  130. // router.StaticFile("favicon.ico", "./resources/favicon.ico")
  131. func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {
  132. return group.staticFileHandler(relativePath, func(c *Context) {
  133. c.File(filepath)
  134. })
  135. }
  136. // StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead..
  137. // router.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false})
  138. // Gin by default user: gin.Dir()
  139. func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes {
  140. return group.staticFileHandler(relativePath, func(c *Context) {
  141. c.FileFromFS(filepath, fs)
  142. })
  143. }
  144. func (group *RouterGroup) staticFileHandler(relativePath string, handler HandlerFunc) IRoutes {
  145. if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
  146. panic("URL parameters can not be used when serving a static file")
  147. }
  148. group.GET(relativePath, handler)
  149. group.HEAD(relativePath, handler)
  150. return group.returnObj()
  151. }
  152. // Static serves files from the given file system root.
  153. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  154. // of the Router's NotFound handler.
  155. // To use the operating system's file system implementation,
  156. // use :
  157. // router.Static("/static", "/var/www")
  158. func (group *RouterGroup) Static(relativePath, root string) IRoutes {
  159. return group.StaticFS(relativePath, Dir(root, false))
  160. }
  161. // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
  162. // Gin by default user: gin.Dir()
  163. func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {
  164. if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
  165. panic("URL parameters can not be used when serving a static folder")
  166. }
  167. handler := group.createStaticHandler(relativePath, fs)
  168. urlPattern := path.Join(relativePath, "/*filepath")
  169. // Register GET and HEAD handlers
  170. group.GET(urlPattern, handler)
  171. group.HEAD(urlPattern, handler)
  172. return group.returnObj()
  173. }
  174. func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {
  175. absolutePath := group.calculateAbsolutePath(relativePath)
  176. fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
  177. return func(c *Context) {
  178. if _, noListing := fs.(*onlyFilesFS); noListing {
  179. c.Writer.WriteHeader(http.StatusNotFound)
  180. }
  181. file := c.Param("filepath")
  182. // Check if file exists and/or if we have permission to access it
  183. f, err := fs.Open(file)
  184. if err != nil {
  185. c.Writer.WriteHeader(http.StatusNotFound)
  186. c.handlers = group.engine.noRoute
  187. // Reset index
  188. c.index = -1
  189. return
  190. }
  191. f.Close()
  192. fileServer.ServeHTTP(c.Writer, c.Request)
  193. }
  194. }
  195. func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {
  196. finalSize := len(group.Handlers) + len(handlers)
  197. assert1(finalSize < int(abortIndex), "too many handlers")
  198. mergedHandlers := make(HandlersChain, finalSize)
  199. copy(mergedHandlers, group.Handlers)
  200. copy(mergedHandlers[len(group.Handlers):], handlers)
  201. return mergedHandlers
  202. }
  203. func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {
  204. return joinPaths(group.basePath, relativePath)
  205. }
  206. func (group *RouterGroup) returnObj() IRoutes {
  207. if group.root {
  208. return group.engine
  209. }
  210. return group
  211. }