routergroup.go 7.4 KB

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