routergroup.go 6.0 KB

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