routergroup.go 7.2 KB

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