routergroup.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. "github.com/julienschmidt/httprouter"
  7. "net/http"
  8. "path"
  9. )
  10. // Used internally to configure router, a RouterGroup is associated with a prefix
  11. // and an array of handlers (middlewares)
  12. type RouterGroup struct {
  13. Handlers []HandlerFunc
  14. absolutePath string
  15. engine *Engine
  16. }
  17. // Adds middlewares to the group, see example code in github.
  18. func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
  19. group.Handlers = append(group.Handlers, middlewares...)
  20. }
  21. // Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
  22. // For example, all the routes that use a common middlware for authorization could be grouped.
  23. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
  24. return &RouterGroup{
  25. Handlers: group.combineHandlers(handlers),
  26. absolutePath: group.calculateAbsolutePath(relativePath),
  27. engine: group.engine,
  28. }
  29. }
  30. // Handle registers a new request handle and middlewares with the given path and method.
  31. // The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.
  32. // See the example code in github.
  33. //
  34. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  35. // functions can be used.
  36. //
  37. // This function is intended for bulk loading and to allow the usage of less
  38. // frequently used, non-standardized or custom methods (e.g. for internal
  39. // communication with a proxy).
  40. func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers []HandlerFunc) {
  41. absolutePath := group.calculateAbsolutePath(relativePath)
  42. handlers = group.combineHandlers(handlers)
  43. if IsDebugging() {
  44. nuHandlers := len(handlers)
  45. handlerName := nameOfFunction(handlers[nuHandlers-1])
  46. debugPrint("%-5s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)
  47. }
  48. group.engine.router.Handle(httpMethod, absolutePath, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
  49. context := group.engine.createContext(w, req, params, handlers)
  50. context.Next()
  51. context.Writer.WriteHeaderNow()
  52. group.engine.reuseContext(context)
  53. })
  54. }
  55. // POST is a shortcut for router.Handle("POST", path, handle)
  56. func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) {
  57. group.Handle("POST", relativePath, handlers)
  58. }
  59. // GET is a shortcut for router.Handle("GET", path, handle)
  60. func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) {
  61. group.Handle("GET", relativePath, handlers)
  62. }
  63. // DELETE is a shortcut for router.Handle("DELETE", path, handle)
  64. func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) {
  65. group.Handle("DELETE", relativePath, handlers)
  66. }
  67. // PATCH is a shortcut for router.Handle("PATCH", path, handle)
  68. func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) {
  69. group.Handle("PATCH", relativePath, handlers)
  70. }
  71. // PUT is a shortcut for router.Handle("PUT", path, handle)
  72. func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) {
  73. group.Handle("PUT", relativePath, handlers)
  74. }
  75. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
  76. func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) {
  77. group.Handle("OPTIONS", relativePath, handlers)
  78. }
  79. // HEAD is a shortcut for router.Handle("HEAD", path, handle)
  80. func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) {
  81. group.Handle("HEAD", relativePath, handlers)
  82. }
  83. // LINK is a shortcut for router.Handle("LINK", path, handle)
  84. func (group *RouterGroup) LINK(relativePath string, handlers ...HandlerFunc) {
  85. group.Handle("LINK", relativePath, handlers)
  86. }
  87. // UNLINK is a shortcut for router.Handle("UNLINK", path, handle)
  88. func (group *RouterGroup) UNLINK(relativePath string, handlers ...HandlerFunc) {
  89. group.Handle("UNLINK", relativePath, handlers)
  90. }
  91. // Static serves files from the given file system root.
  92. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  93. // of the Router's NotFound handler.
  94. // To use the operating system's file system implementation,
  95. // use :
  96. // router.Static("/static", "/var/www")
  97. func (group *RouterGroup) Static(relativePath, root string) {
  98. absolutePath := group.calculateAbsolutePath(relativePath)
  99. handler := group.createStaticHandler(absolutePath, root)
  100. absolutePath = path.Join(absolutePath, "/*filepath")
  101. // Register GET and HEAD handlers
  102. group.GET(absolutePath, handler)
  103. group.HEAD(absolutePath, handler)
  104. }
  105. func (group *RouterGroup) createStaticHandler(absolutePath, root string) func(*Context) {
  106. fileServer := http.StripPrefix(absolutePath, http.FileServer(http.Dir(root)))
  107. return func(c *Context) {
  108. fileServer.ServeHTTP(c.Writer, c.Request)
  109. }
  110. }
  111. func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {
  112. finalSize := len(group.Handlers) + len(handlers)
  113. mergedHandlers := make([]HandlerFunc, 0, finalSize)
  114. mergedHandlers = append(mergedHandlers, group.Handlers...)
  115. return append(mergedHandlers, handlers...)
  116. }
  117. func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {
  118. if len(relativePath) == 0 {
  119. return group.absolutePath
  120. }
  121. absolutePath := path.Join(group.absolutePath, relativePath)
  122. appendSlash := lastChar(relativePath) == '/' && lastChar(absolutePath) != '/'
  123. if appendSlash {
  124. return absolutePath + "/"
  125. }
  126. return absolutePath
  127. }