gin.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. "html/template"
  7. "net/http"
  8. "sync"
  9. "github.com/gin-gonic/gin/binding"
  10. "github.com/gin-gonic/gin/render"
  11. )
  12. var default404Body = []byte("404 page not found")
  13. var default405Body = []byte("405 method not allowed")
  14. type (
  15. HandlerFunc func(*Context)
  16. HandlersChain []HandlerFunc
  17. // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.
  18. Engine struct {
  19. RouterGroup
  20. HTMLRender render.Render
  21. pool sync.Pool
  22. allNoRoute HandlersChain
  23. allNoMethod HandlersChain
  24. noRoute HandlersChain
  25. noMethod HandlersChain
  26. trees map[string]*node
  27. // Enables automatic redirection if the current route can't be matched but a
  28. // handler for the path with (without) the trailing slash exists.
  29. // For example if /foo/ is requested but a route only exists for /foo, the
  30. // client is redirected to /foo with http status code 301 for GET requests
  31. // and 307 for all other request methods.
  32. RedirectTrailingSlash bool
  33. // If enabled, the router tries to fix the current request path, if no
  34. // handle is registered for it.
  35. // First superfluous path elements like ../ or // are removed.
  36. // Afterwards the router does a case-insensitive lookup of the cleaned path.
  37. // If a handle can be found for this route, the router makes a redirection
  38. // to the corrected path with status code 301 for GET requests and 307 for
  39. // all other request methods.
  40. // For example /FOO and /..//Foo could be redirected to /foo.
  41. // RedirectTrailingSlash is independent of this option.
  42. RedirectFixedPath bool
  43. // If enabled, the router checks if another method is allowed for the
  44. // current route, if the current request can not be routed.
  45. // If this is the case, the request is answered with 'Method Not Allowed'
  46. // and HTTP status code 405.
  47. // If no other Method is allowed, the request is delegated to the NotFound
  48. // handler.
  49. HandleMethodNotAllowed bool
  50. }
  51. )
  52. // Returns a new blank Engine instance without any middleware attached.
  53. // The most basic configuration
  54. func New() *Engine {
  55. engine := &Engine{
  56. RouterGroup: RouterGroup{
  57. Handlers: nil,
  58. absolutePath: "/",
  59. },
  60. RedirectTrailingSlash: true,
  61. RedirectFixedPath: true,
  62. HandleMethodNotAllowed: true,
  63. trees: make(map[string]*node),
  64. }
  65. engine.RouterGroup.engine = engine
  66. engine.pool.New = func() interface{} {
  67. return engine.allocateContext()
  68. }
  69. return engine
  70. }
  71. // Returns a Engine instance with the Logger and Recovery already attached.
  72. func Default() *Engine {
  73. engine := New()
  74. engine.Use(Recovery(), Logger())
  75. return engine
  76. }
  77. func (engine *Engine) allocateContext() (context *Context) {
  78. return &Context{Engine: engine}
  79. }
  80. func (engine *Engine) LoadHTMLGlob(pattern string) {
  81. if IsDebugging() {
  82. engine.HTMLRender = &render.HTMLDebugRender{Glob: pattern}
  83. } else {
  84. templ := template.Must(template.ParseGlob(pattern))
  85. engine.SetHTMLTemplate(templ)
  86. }
  87. }
  88. func (engine *Engine) LoadHTMLFiles(files ...string) {
  89. if IsDebugging() {
  90. engine.HTMLRender = &render.HTMLDebugRender{Files: files}
  91. } else {
  92. templ := template.Must(template.ParseFiles(files...))
  93. engine.SetHTMLTemplate(templ)
  94. }
  95. }
  96. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  97. engine.HTMLRender = render.HTMLRender{Template: templ}
  98. }
  99. // Adds handlers for NoRoute. It return a 404 code by default.
  100. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  101. engine.noRoute = handlers
  102. engine.rebuild404Handlers()
  103. }
  104. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  105. engine.noMethod = handlers
  106. engine.rebuild405Handlers()
  107. }
  108. func (engine *Engine) Use(middlewares ...HandlerFunc) {
  109. engine.RouterGroup.Use(middlewares...)
  110. engine.rebuild404Handlers()
  111. engine.rebuild405Handlers()
  112. }
  113. func (engine *Engine) rebuild404Handlers() {
  114. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  115. }
  116. func (engine *Engine) rebuild405Handlers() {
  117. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  118. }
  119. func (engine *Engine) handle(method, path string, handlers HandlersChain) {
  120. if path[0] != '/' {
  121. panic("path must begin with '/'")
  122. }
  123. if method == "" {
  124. panic("HTTP method can not be empty")
  125. }
  126. if len(handlers) == 0 {
  127. panic("there must be at least one handler")
  128. }
  129. root := engine.trees[method]
  130. if root == nil {
  131. root = new(node)
  132. engine.trees[method] = root
  133. }
  134. root.addRoute(path, handlers)
  135. }
  136. func (engine *Engine) Run(addr string) error {
  137. debugPrint("[WARNING] Running in DEBUG mode! Disable it before going production")
  138. debugPrint("Listening and serving HTTP on %s\n", addr)
  139. return http.ListenAndServe(addr, engine)
  140. }
  141. func (engine *Engine) RunTLS(addr string, cert string, key string) error {
  142. debugPrint("[WARNING] Running in DEBUG mode! Disable it before going production")
  143. debugPrint("Listening and serving HTTPS on %s\n", addr)
  144. return http.ListenAndServeTLS(addr, cert, key, engine)
  145. }
  146. // ServeHTTP makes the router implement the http.Handler interface.
  147. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  148. context := engine.pool.Get().(*Context)
  149. context.writermem.reset(w)
  150. context.Request = req
  151. context.reset()
  152. engine.serveHTTPRequest(context)
  153. engine.pool.Put(context)
  154. }
  155. func (engine *Engine) serveHTTPRequest(context *Context) {
  156. httpMethod := context.Request.Method
  157. path := context.Request.URL.Path
  158. // Find root of the tree for the given HTTP method
  159. if root := engine.trees[httpMethod]; root != nil {
  160. // Find route in tree
  161. handlers, params, tsr := root.getValue(path, context.Params)
  162. // Dispatch if we found any handlers
  163. if handlers != nil {
  164. context.handlers = handlers
  165. context.Params = params
  166. context.Next()
  167. context.writermem.WriteHeaderNow()
  168. return
  169. } else if httpMethod != "CONNECT" && path != "/" {
  170. if engine.serveAutoRedirect(context, root, tsr) {
  171. return
  172. }
  173. }
  174. }
  175. if engine.HandleMethodNotAllowed {
  176. for method, root := range engine.trees {
  177. if method != httpMethod {
  178. if handlers, _, _ := root.getValue(path, nil); handlers != nil {
  179. context.handlers = engine.allNoMethod
  180. serveError(context, 405, default405Body)
  181. return
  182. }
  183. }
  184. }
  185. }
  186. context.handlers = engine.allNoRoute
  187. serveError(context, 404, default404Body)
  188. }
  189. func (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {
  190. req := c.Request
  191. path := req.URL.Path
  192. code := 301 // Permanent redirect, request with GET method
  193. if req.Method != "GET" {
  194. code = 307
  195. }
  196. if tsr && engine.RedirectTrailingSlash {
  197. if len(path) > 1 && path[len(path)-1] == '/' {
  198. req.URL.Path = path[:len(path)-1]
  199. } else {
  200. req.URL.Path = path + "/"
  201. }
  202. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  203. http.Redirect(c.Writer, req, req.URL.String(), code)
  204. c.writermem.WriteHeaderNow()
  205. return true
  206. }
  207. // Try to fix the request path
  208. if engine.RedirectFixedPath {
  209. fixedPath, found := root.findCaseInsensitivePath(
  210. CleanPath(path),
  211. engine.RedirectTrailingSlash,
  212. )
  213. if found {
  214. req.URL.Path = string(fixedPath)
  215. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  216. http.Redirect(c.Writer, req, req.URL.String(), code)
  217. c.writermem.WriteHeaderNow()
  218. return true
  219. }
  220. }
  221. return false
  222. }
  223. func serveError(c *Context, code int, defaultMessage []byte) {
  224. c.writermem.status = code
  225. c.Next()
  226. if !c.Writer.Written() {
  227. if c.Writer.Status() == code {
  228. c.Data(-1, binding.MIMEPlain, defaultMessage)
  229. } else {
  230. c.Writer.WriteHeaderNow()
  231. }
  232. }
  233. }