gin.go 8.0 KB

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