gin.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. debugPrintWARNING()
  56. engine := &Engine{
  57. RouterGroup: RouterGroup{
  58. Handlers: nil,
  59. absolutePath: "/",
  60. },
  61. RedirectTrailingSlash: true,
  62. RedirectFixedPath: true,
  63. HandleMethodNotAllowed: true,
  64. trees: make(map[string]*node),
  65. }
  66. engine.RouterGroup.engine = engine
  67. engine.pool.New = func() interface{} {
  68. return engine.allocateContext()
  69. }
  70. return engine
  71. }
  72. // Returns a Engine instance with the Logger and Recovery already attached.
  73. func Default() *Engine {
  74. engine := New()
  75. engine.Use(Recovery(), Logger())
  76. return engine
  77. }
  78. func (engine *Engine) allocateContext() (context *Context) {
  79. return &Context{Engine: engine}
  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{Template: templ}
  99. }
  100. // Adds handlers for NoRoute. It return a 404 code by default.
  101. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  102. engine.noRoute = handlers
  103. engine.rebuild404Handlers()
  104. }
  105. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  106. engine.noMethod = handlers
  107. engine.rebuild405Handlers()
  108. }
  109. func (engine *Engine) Use(middlewares ...HandlerFunc) {
  110. engine.RouterGroup.Use(middlewares...)
  111. engine.rebuild404Handlers()
  112. engine.rebuild405Handlers()
  113. }
  114. func (engine *Engine) rebuild404Handlers() {
  115. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  116. }
  117. func (engine *Engine) rebuild405Handlers() {
  118. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  119. }
  120. func (engine *Engine) handle(method, path string, handlers HandlersChain) {
  121. if path[0] != '/' {
  122. panic("path must begin with '/'")
  123. }
  124. if method == "" {
  125. panic("HTTP method can not be empty")
  126. }
  127. if len(handlers) == 0 {
  128. panic("there must be at least one handler")
  129. }
  130. root := engine.trees[method]
  131. if root == nil {
  132. root = new(node)
  133. engine.trees[method] = root
  134. }
  135. root.addRoute(path, handlers)
  136. }
  137. func (engine *Engine) Run(addr string) (err error) {
  138. debugPrint("Listening and serving HTTP on %s\n", addr)
  139. defer debugPrintError(err)
  140. err = http.ListenAndServe(addr, engine)
  141. return
  142. }
  143. func (engine *Engine) RunTLS(addr string, cert string, key string) (err error) {
  144. debugPrint("Listening and serving HTTPS on %s\n", addr)
  145. defer debugPrintError(err)
  146. err = http.ListenAndServe(addr, engine)
  147. return
  148. }
  149. // ServeHTTP makes the router implement the http.Handler interface.
  150. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  151. context := engine.pool.Get().(*Context)
  152. context.writermem.reset(w)
  153. context.Request = req
  154. context.reset()
  155. engine.serveHTTPRequest(context)
  156. engine.pool.Put(context)
  157. }
  158. func (engine *Engine) serveHTTPRequest(context *Context) {
  159. httpMethod := context.Request.Method
  160. path := context.Request.URL.Path
  161. // Find root of the tree for the given HTTP method
  162. if root := engine.trees[httpMethod]; root != nil {
  163. // Find route in tree
  164. handlers, params, tsr := root.getValue(path, context.Params)
  165. // Dispatch if we found any handlers
  166. if handlers != nil {
  167. context.handlers = handlers
  168. context.Params = params
  169. context.Next()
  170. context.writermem.WriteHeaderNow()
  171. return
  172. } else if httpMethod != "CONNECT" && path != "/" {
  173. if engine.serveAutoRedirect(context, root, tsr) {
  174. return
  175. }
  176. }
  177. }
  178. if engine.HandleMethodNotAllowed {
  179. for method, root := range engine.trees {
  180. if method != httpMethod {
  181. if handlers, _, _ := root.getValue(path, nil); handlers != nil {
  182. context.handlers = engine.allNoMethod
  183. serveError(context, 405, default405Body)
  184. return
  185. }
  186. }
  187. }
  188. }
  189. context.handlers = engine.allNoRoute
  190. serveError(context, 404, default404Body)
  191. }
  192. func (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {
  193. req := c.Request
  194. path := req.URL.Path
  195. code := 301 // Permanent redirect, request with GET method
  196. if req.Method != "GET" {
  197. code = 307
  198. }
  199. if tsr && engine.RedirectTrailingSlash {
  200. if len(path) > 1 && path[len(path)-1] == '/' {
  201. req.URL.Path = path[:len(path)-1]
  202. } else {
  203. req.URL.Path = path + "/"
  204. }
  205. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  206. http.Redirect(c.Writer, req, req.URL.String(), code)
  207. c.writermem.WriteHeaderNow()
  208. return true
  209. }
  210. // Try to fix the request path
  211. if engine.RedirectFixedPath {
  212. fixedPath, found := root.findCaseInsensitivePath(
  213. CleanPath(path),
  214. engine.RedirectTrailingSlash,
  215. )
  216. if found {
  217. req.URL.Path = string(fixedPath)
  218. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  219. http.Redirect(c.Writer, req, req.URL.String(), code)
  220. c.writermem.WriteHeaderNow()
  221. return true
  222. }
  223. }
  224. return false
  225. }
  226. func serveError(c *Context, code int, defaultMessage []byte) {
  227. c.writermem.status = code
  228. c.Next()
  229. if !c.Writer.Written() {
  230. if c.Writer.Status() == code {
  231. c.Data(-1, binding.MIMEPlain, defaultMessage)
  232. } else {
  233. c.Writer.WriteHeaderNow()
  234. }
  235. }
  236. }