routergroup.go 8.1 KB

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