gin.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. context = &Context{Engine: engine}
  78. context.Input = inputHolder{context: context}
  79. return
  80. }
  81. func (engine *Engine) LoadHTMLGlob(pattern string) {
  82. if IsDebugging() {
  83. engine.HTMLRender = &render.HTMLDebugRender{Glob: pattern}
  84. } else {
  85. templ := template.Must(template.ParseGlob(pattern))
  86. engine.SetHTMLTemplate(templ)
  87. }
  88. }
  89. func (engine *Engine) LoadHTMLFiles(files ...string) {
  90. if IsDebugging() {
  91. engine.HTMLRender = &render.HTMLDebugRender{Files: files}
  92. } else {
  93. templ := template.Must(template.ParseFiles(files...))
  94. engine.SetHTMLTemplate(templ)
  95. }
  96. }
  97. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  98. engine.HTMLRender = render.HTMLRender{
  99. Template: templ,
  100. }
  101. }
  102. // Adds handlers for NoRoute. It return a 404 code by default.
  103. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  104. engine.noRoute = handlers
  105. engine.rebuild404Handlers()
  106. }
  107. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  108. engine.noMethod = handlers
  109. engine.rebuild405Handlers()
  110. }
  111. func (engine *Engine) Use(middlewares ...HandlerFunc) {
  112. engine.RouterGroup.Use(middlewares...)
  113. engine.rebuild404Handlers()
  114. engine.rebuild405Handlers()
  115. }
  116. func (engine *Engine) rebuild404Handlers() {
  117. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  118. }
  119. func (engine *Engine) rebuild405Handlers() {
  120. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  121. }
  122. func (engine *Engine) handle(method, path string, handlers []HandlerFunc) {
  123. if path[0] != '/' {
  124. panic("path must begin with '/'")
  125. }
  126. root := engine.trees[method]
  127. if root == nil {
  128. root = new(node)
  129. engine.trees[method] = root
  130. }
  131. root.addRoute(path, handlers)
  132. }
  133. func (engine *Engine) Run(addr string) error {
  134. debugPrint("Listening and serving HTTP on %s\n", addr)
  135. return http.ListenAndServe(addr, engine)
  136. }
  137. func (engine *Engine) RunTLS(addr string, cert string, key string) error {
  138. debugPrint("Listening and serving HTTPS on %s\n", addr)
  139. return http.ListenAndServeTLS(addr, cert, key, engine)
  140. }
  141. // ServeHTTP makes the router implement the http.Handler interface.
  142. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  143. context := engine.pool.Get().(*Context)
  144. context.writermem.reset(w)
  145. context.Request = req
  146. context.reset()
  147. engine.serveHTTPRequest(context)
  148. engine.pool.Put(context)
  149. }
  150. func (engine *Engine) serveHTTPRequest(context *Context) {
  151. httpMethod := context.Request.Method
  152. path := context.Request.URL.Path
  153. // Find root of the tree for the given HTTP method
  154. if root := engine.trees[httpMethod]; root != nil {
  155. // Find route in tree
  156. handlers, params, tsr := root.getValue(path, context.Params)
  157. // Dispatch if we found any handlers
  158. if handlers != nil {
  159. context.handlers = handlers
  160. context.Params = params
  161. context.Next()
  162. context.writermem.WriteHeaderNow()
  163. return
  164. } else if httpMethod != "CONNECT" && path != "/" {
  165. if engine.serveAutoRedirect(context, root, tsr) {
  166. return
  167. }
  168. }
  169. }
  170. if engine.HandleMethodNotAllowed {
  171. for method, root := range engine.trees {
  172. if method != httpMethod {
  173. if handlers, _, _ := root.getValue(path, nil); handlers != nil {
  174. context.handlers = engine.allNoMethod
  175. serveError(context, 405, default405Body)
  176. return
  177. }
  178. }
  179. }
  180. }
  181. context.handlers = engine.allNoRoute
  182. serveError(context, 404, default404Body)
  183. }
  184. func (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {
  185. req := c.Request
  186. path := req.URL.Path
  187. code := 301 // Permanent redirect, request with GET method
  188. if req.Method != "GET" {
  189. code = 307
  190. }
  191. if tsr && engine.RedirectTrailingSlash {
  192. if len(path) > 1 && path[len(path)-1] == '/' {
  193. req.URL.Path = path[:len(path)-1]
  194. } else {
  195. req.URL.Path = path + "/"
  196. }
  197. http.Redirect(c.Writer, req, req.URL.String(), code)
  198. return true
  199. }
  200. // Try to fix the request path
  201. if engine.RedirectFixedPath {
  202. fixedPath, found := root.findCaseInsensitivePath(
  203. CleanPath(path),
  204. engine.RedirectTrailingSlash,
  205. )
  206. if found {
  207. req.URL.Path = string(fixedPath)
  208. http.Redirect(c.Writer, req, req.URL.String(), code)
  209. return true
  210. }
  211. }
  212. return false
  213. }
  214. func serveError(c *Context, code int, defaultMessage []byte) {
  215. c.writermem.status = code
  216. c.Next()
  217. if !c.Writer.Written() {
  218. if c.Writer.Status() == code {
  219. c.Data(-1, binding.MIMEPlain, defaultMessage)
  220. } else {
  221. c.Writer.WriteHeaderNow()
  222. }
  223. }
  224. }