gin.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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.HTMLRender
  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. BasePath: "/",
  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.HTMLDebug{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.HTMLDebug{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.HTMLProduction{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. c := engine.getcontext(w, req)
  152. engine.handleHTTPRequest(c)
  153. engine.putcontext(c)
  154. }
  155. func (engine *Engine) getcontext(w http.ResponseWriter, req *http.Request) *Context {
  156. c := engine.pool.Get().(*Context)
  157. c.writermem.reset(w)
  158. c.Request = req
  159. c.reset()
  160. return c
  161. }
  162. func (engine *Engine) putcontext(c *Context) {
  163. engine.pool.Put(c)
  164. }
  165. func (engine *Engine) handleHTTPRequest(context *Context) {
  166. httpMethod := context.Request.Method
  167. path := context.Request.URL.Path
  168. // Find root of the tree for the given HTTP method
  169. if root := engine.trees[httpMethod]; root != nil {
  170. // Find route in tree
  171. handlers, params, tsr := root.getValue(path, context.Params)
  172. if handlers != nil {
  173. context.handlers = handlers
  174. context.Params = params
  175. context.Next()
  176. context.writermem.WriteHeaderNow()
  177. return
  178. } else if httpMethod != "CONNECT" && path != "/" {
  179. if engine.serveAutoRedirect(context, root, tsr) {
  180. return
  181. }
  182. }
  183. }
  184. if engine.HandleMethodNotAllowed {
  185. for method, root := range engine.trees {
  186. if method != httpMethod {
  187. if handlers, _, _ := root.getValue(path, nil); handlers != nil {
  188. context.handlers = engine.allNoMethod
  189. serveError(context, 405, default405Body)
  190. return
  191. }
  192. }
  193. }
  194. }
  195. context.handlers = engine.allNoRoute
  196. serveError(context, 404, default404Body)
  197. }
  198. func (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {
  199. req := c.Request
  200. path := req.URL.Path
  201. code := 301 // Permanent redirect, request with GET method
  202. if req.Method != "GET" {
  203. code = 307
  204. }
  205. if tsr && engine.RedirectTrailingSlash {
  206. if len(path) > 1 && path[len(path)-1] == '/' {
  207. req.URL.Path = path[:len(path)-1]
  208. } else {
  209. req.URL.Path = path + "/"
  210. }
  211. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  212. http.Redirect(c.Writer, req, req.URL.String(), code)
  213. c.writermem.WriteHeaderNow()
  214. return true
  215. }
  216. // Try to fix the request path
  217. if engine.RedirectFixedPath {
  218. fixedPath, found := root.findCaseInsensitivePath(
  219. CleanPath(path),
  220. engine.RedirectTrailingSlash,
  221. )
  222. if found {
  223. req.URL.Path = string(fixedPath)
  224. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  225. http.Redirect(c.Writer, req, req.URL.String(), code)
  226. c.writermem.WriteHeaderNow()
  227. return true
  228. }
  229. }
  230. return false
  231. }
  232. func serveError(c *Context, code int, defaultMessage []byte) {
  233. c.writermem.status = code
  234. c.Next()
  235. if !c.Writer.Written() {
  236. if c.Writer.Status() == code {
  237. c.Data(-1, binding.MIMEPlain, defaultMessage)
  238. } else {
  239. c.Writer.WriteHeaderNow()
  240. }
  241. }
  242. }