gin.go 7.9 KB

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