gin.go 7.6 KB

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