gin.go 7.6 KB

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