gin.go 7.4 KB

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