gin.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 i := range ps {
  25. if ps[i].Key == name {
  26. return ps[i].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. RedirectTrailingSlash: true,
  75. RedirectFixedPath: true,
  76. HandleMethodNotAllowed: true,
  77. trees: make(map[string]*node),
  78. }
  79. engine.RouterGroup = &RouterGroup{
  80. Handlers: nil,
  81. absolutePath: "/",
  82. engine: engine,
  83. }
  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.Writer = &context.writermem
  98. context.Input = inputHolder{context: context}
  99. return
  100. }
  101. func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request) *Context {
  102. c := engine.pool.Get().(*Context)
  103. c.reset()
  104. c.writermem.reset(w)
  105. c.Request = req
  106. return c
  107. }
  108. func (engine *Engine) reuseContext(c *Context) {
  109. engine.pool.Put(c)
  110. }
  111. func (engine *Engine) LoadHTMLGlob(pattern string) {
  112. if IsDebugging() {
  113. r := &render.HTMLDebugRender{Glob: pattern}
  114. engine.HTMLRender = r
  115. } else {
  116. templ := template.Must(template.ParseGlob(pattern))
  117. engine.SetHTMLTemplate(templ)
  118. }
  119. }
  120. func (engine *Engine) LoadHTMLFiles(files ...string) {
  121. if IsDebugging() {
  122. r := &render.HTMLDebugRender{Files: files}
  123. engine.HTMLRender = r
  124. } else {
  125. templ := template.Must(template.ParseFiles(files...))
  126. engine.SetHTMLTemplate(templ)
  127. }
  128. }
  129. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  130. engine.HTMLRender = render.HTMLRender{
  131. Template: templ,
  132. }
  133. }
  134. // Adds handlers for NoRoute. It return a 404 code by default.
  135. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  136. engine.noRoute = handlers
  137. engine.rebuild404Handlers()
  138. }
  139. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  140. engine.noMethod = handlers
  141. engine.rebuild405Handlers()
  142. }
  143. func (engine *Engine) Use(middlewares ...HandlerFunc) {
  144. engine.RouterGroup.Use(middlewares...)
  145. engine.rebuild404Handlers()
  146. engine.rebuild405Handlers()
  147. }
  148. func (engine *Engine) rebuild404Handlers() {
  149. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  150. }
  151. func (engine *Engine) rebuild405Handlers() {
  152. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  153. }
  154. func (engine *Engine) handle404(c *Context) {
  155. // set 404 by default, useful for logging
  156. c.handlers = engine.allNoRoute
  157. c.Writer.WriteHeader(404)
  158. c.Next()
  159. if !c.Writer.Written() {
  160. if c.Writer.Status() == 404 {
  161. c.Data(-1, binding.MIMEPlain, default404Body)
  162. } else {
  163. c.Writer.WriteHeaderNow()
  164. }
  165. }
  166. }
  167. func (engine *Engine) handle405(c *Context) {
  168. // set 405 by default, useful for logging
  169. c.handlers = engine.allNoMethod
  170. c.Writer.WriteHeader(405)
  171. c.Next()
  172. if !c.Writer.Written() {
  173. if c.Writer.Status() == 405 {
  174. c.Data(-1, binding.MIMEPlain, default405Body)
  175. } else {
  176. c.Writer.WriteHeaderNow()
  177. }
  178. }
  179. }
  180. func (engine *Engine) handle(method, path string, handlers []HandlerFunc) {
  181. if path[0] != '/' {
  182. panic("path must begin with '/'")
  183. }
  184. //methodCode := codeForHTTPMethod(method)
  185. root := engine.trees[method]
  186. if root == nil {
  187. root = new(node)
  188. engine.trees[method] = root
  189. }
  190. root.addRoute(path, handlers)
  191. }
  192. // ServeHTTP makes the router implement the http.Handler interface.
  193. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  194. c := engine.createContext(w, req)
  195. //methodCode := codeForHTTPMethod(req.Method)
  196. if root := engine.trees[req.Method]; root != nil {
  197. path := req.URL.Path
  198. if handlers, params, _ := root.getValue(path, c.Params); handlers != nil {
  199. c.handlers = handlers
  200. c.Params = params
  201. c.Next()
  202. engine.reuseContext(c)
  203. return
  204. }
  205. }
  206. // Handle 404
  207. engine.handle404(c)
  208. engine.reuseContext(c)
  209. }
  210. func (engine *Engine) Run(addr string) error {
  211. debugPrint("Listening and serving HTTP on %s\n", addr)
  212. return http.ListenAndServe(addr, engine)
  213. }
  214. func (engine *Engine) RunTLS(addr string, cert string, key string) error {
  215. debugPrint("Listening and serving HTTPS on %s\n", addr)
  216. return http.ListenAndServeTLS(addr, cert, key, engine)
  217. }