gin.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. allNoRoute HandlersChain
  25. allNoMethod HandlersChain
  26. noRoute HandlersChain
  27. noMethod HandlersChain
  28. pool sync.Pool
  29. trees methodTrees
  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(methodTrees, 0, 6),
  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. // Sets the handlers called when... TODO
  109. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  110. engine.noMethod = handlers
  111. engine.rebuild405Handlers()
  112. }
  113. // Attachs a global middleware to the router. ie. the middlewares attached though Use() will be
  114. // included in the handlers chain for every single request. Even 404, 405, static files...
  115. // For example, this is the right place for a logger or error management middleware.
  116. func (engine *Engine) Use(middlewares ...HandlerFunc) {
  117. engine.RouterGroup.Use(middlewares...)
  118. engine.rebuild404Handlers()
  119. engine.rebuild405Handlers()
  120. }
  121. func (engine *Engine) rebuild404Handlers() {
  122. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  123. }
  124. func (engine *Engine) rebuild405Handlers() {
  125. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  126. }
  127. func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
  128. debugPrintRoute(method, path, handlers)
  129. if path[0] != '/' {
  130. panic("path must begin with '/'")
  131. }
  132. if method == "" {
  133. panic("HTTP method can not be empty")
  134. }
  135. if len(handlers) == 0 {
  136. panic("there must be at least one handler")
  137. }
  138. root := engine.trees.get("method")
  139. if root == nil {
  140. root = new(node)
  141. engine.trees = append(engine.trees, methodTree{
  142. method: method,
  143. root: root,
  144. })
  145. }
  146. root.addRoute(path, handlers)
  147. }
  148. // The router is attached to a http.Server and starts listening and serving HTTP requests.
  149. // It is a shortcut for http.ListenAndServe(addr, router)
  150. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  151. func (engine *Engine) Run(addr string) (err error) {
  152. debugPrint("Listening and serving HTTP on %s\n", addr)
  153. defer func() { debugPrintError(err) }()
  154. err = http.ListenAndServe(addr, engine)
  155. return
  156. }
  157. // The router is attached to a http.Server and starts listening and serving HTTPS requests.
  158. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
  159. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  160. func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {
  161. debugPrint("Listening and serving HTTPS on %s\n", addr)
  162. defer func() { debugPrintError(err) }()
  163. err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
  164. return
  165. }
  166. // The router is attached to a http.Server and starts listening and serving HTTP requests
  167. // through the specified unix socket (ie. a file)
  168. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  169. func (engine *Engine) RunUnix(file string) (err error) {
  170. debugPrint("Listening and serving HTTP on unix:/%s", file)
  171. defer func() { debugPrintError(err) }()
  172. os.Remove(file)
  173. listener, err := net.Listen("unix", file)
  174. if err != nil {
  175. return
  176. }
  177. defer listener.Close()
  178. err = http.Serve(listener, engine)
  179. return
  180. }
  181. // Conforms to the http.Handler interface.
  182. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  183. c := engine.pool.Get().(*Context)
  184. c.writermem.reset(w)
  185. c.Request = req
  186. c.reset()
  187. engine.handleHTTPRequest(c)
  188. engine.pool.Put(c)
  189. }
  190. func (engine *Engine) handleHTTPRequest(context *Context) {
  191. httpMethod := context.Request.Method
  192. path := context.Request.URL.Path
  193. // Find root of the tree for the given HTTP method
  194. t := engine.trees
  195. for i, tl := 0, len(t); i < tl; i++ {
  196. if t[i].method == httpMethod {
  197. // Find route in tree
  198. handlers, params, tsr := t[i].root.getValue(path, context.Params)
  199. if handlers != nil {
  200. context.handlers = handlers
  201. context.Params = params
  202. context.Next()
  203. context.writermem.WriteHeaderNow()
  204. return
  205. } else if httpMethod != "CONNECT" && path != "/" {
  206. if engine.serveAutoRedirect(context, t[i].root, tsr) {
  207. return
  208. }
  209. }
  210. }
  211. }
  212. // TODO: unit test
  213. if engine.HandleMethodNotAllowed {
  214. for _, tree := range engine.trees {
  215. if tree.method != httpMethod {
  216. if handlers, _, _ := tree.root.getValue(path, nil); handlers != nil {
  217. context.handlers = engine.allNoMethod
  218. serveError(context, 405, default405Body)
  219. return
  220. }
  221. }
  222. }
  223. }
  224. context.handlers = engine.allNoRoute
  225. serveError(context, 404, default404Body)
  226. }
  227. func (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {
  228. req := c.Request
  229. path := req.URL.Path
  230. code := 301 // Permanent redirect, request with GET method
  231. if req.Method != "GET" {
  232. code = 307
  233. }
  234. if tsr && engine.RedirectTrailingSlash {
  235. if len(path) > 1 && path[len(path)-1] == '/' {
  236. req.URL.Path = path[:len(path)-1]
  237. } else {
  238. req.URL.Path = path + "/"
  239. }
  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. // Try to fix the request path
  246. if engine.RedirectFixedPath {
  247. fixedPath, found := root.findCaseInsensitivePath(
  248. CleanPath(path),
  249. engine.RedirectTrailingSlash,
  250. )
  251. if found {
  252. req.URL.Path = string(fixedPath)
  253. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  254. http.Redirect(c.Writer, req, req.URL.String(), code)
  255. c.writermem.WriteHeaderNow()
  256. return true
  257. }
  258. }
  259. return false
  260. }
  261. func serveError(c *Context, code int, defaultMessage []byte) {
  262. c.writermem.status = code
  263. c.Next()
  264. if !c.Writer.Written() {
  265. if c.Writer.Status() == code {
  266. c.Data(-1, binding.MIMEPlain, defaultMessage)
  267. } else {
  268. c.Writer.WriteHeaderNow()
  269. }
  270. }
  271. }