gin.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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/render"
  12. )
  13. const defaultMultipartMemory = 32 << 20 // 32 MB
  14. var (
  15. default404Body = []byte("404 page not found")
  16. default405Body = []byte("405 method not allowed")
  17. defaultAppEngine bool
  18. )
  19. // HandlerFunc defines the handler used by gin middleware as return value.
  20. type HandlerFunc func(*Context)
  21. // HandlersChain defines a HandlerFunc array.
  22. type HandlersChain []HandlerFunc
  23. // Last returns the last handler in the chain. ie. the last handler is the main own.
  24. func (c HandlersChain) Last() HandlerFunc {
  25. if length := len(c); length > 0 {
  26. return c[length-1]
  27. }
  28. return nil
  29. }
  30. // RouteInfo represents a request route's specification which contains method and path and its handler.
  31. type RouteInfo struct {
  32. Method string
  33. Path string
  34. Handler string
  35. HandlerFunc HandlerFunc
  36. }
  37. // RoutesInfo defines a RouteInfo array.
  38. type RoutesInfo []RouteInfo
  39. // Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
  40. // Create an instance of Engine, by using New() or Default()
  41. type Engine struct {
  42. RouterGroup
  43. // Enables automatic redirection if the current route can't be matched but a
  44. // handler for the path with (without) the trailing slash exists.
  45. // For example if /foo/ is requested but a route only exists for /foo, the
  46. // client is redirected to /foo with http status code 301 for GET requests
  47. // and 307 for all other request methods.
  48. RedirectTrailingSlash bool
  49. // If enabled, the router tries to fix the current request path, if no
  50. // handle is registered for it.
  51. // First superfluous path elements like ../ or // are removed.
  52. // Afterwards the router does a case-insensitive lookup of the cleaned path.
  53. // If a handle can be found for this route, the router makes a redirection
  54. // to the corrected path with status code 301 for GET requests and 307 for
  55. // all other request methods.
  56. // For example /FOO and /..//Foo could be redirected to /foo.
  57. // RedirectTrailingSlash is independent of this option.
  58. RedirectFixedPath bool
  59. // If enabled, the router checks if another method is allowed for the
  60. // current route, if the current request can not be routed.
  61. // If this is the case, the request is answered with 'Method Not Allowed'
  62. // and HTTP status code 405.
  63. // If no other Method is allowed, the request is delegated to the NotFound
  64. // handler.
  65. HandleMethodNotAllowed bool
  66. ForwardedByClientIP bool
  67. // #726 #755 If enabled, it will thrust some headers starting with
  68. // 'X-AppEngine...' for better integration with that PaaS.
  69. AppEngine bool
  70. // If enabled, the url.RawPath will be used to find parameters.
  71. UseRawPath bool
  72. // If true, the path value will be unescaped.
  73. // If UseRawPath is false (by default), the UnescapePathValues effectively is true,
  74. // as url.Path gonna be used, which is already unescaped.
  75. UnescapePathValues bool
  76. // Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm
  77. // method call.
  78. MaxMultipartMemory int64
  79. delims render.Delims
  80. secureJsonPrefix string
  81. HTMLRender render.HTMLRender
  82. FuncMap template.FuncMap
  83. allNoRoute HandlersChain
  84. allNoMethod HandlersChain
  85. noRoute HandlersChain
  86. noMethod HandlersChain
  87. pool sync.Pool
  88. trees methodTrees
  89. }
  90. var _ IRouter = &Engine{}
  91. // New returns a new blank Engine instance without any middleware attached.
  92. // By default the configuration is:
  93. // - RedirectTrailingSlash: true
  94. // - RedirectFixedPath: false
  95. // - HandleMethodNotAllowed: false
  96. // - ForwardedByClientIP: true
  97. // - UseRawPath: false
  98. // - UnescapePathValues: true
  99. func New() *Engine {
  100. debugPrintWARNINGNew()
  101. engine := &Engine{
  102. RouterGroup: RouterGroup{
  103. Handlers: nil,
  104. basePath: "/",
  105. root: true,
  106. },
  107. FuncMap: template.FuncMap{},
  108. RedirectTrailingSlash: true,
  109. RedirectFixedPath: false,
  110. HandleMethodNotAllowed: false,
  111. ForwardedByClientIP: true,
  112. AppEngine: defaultAppEngine,
  113. UseRawPath: false,
  114. UnescapePathValues: true,
  115. MaxMultipartMemory: defaultMultipartMemory,
  116. trees: make(methodTrees, 0, 9),
  117. delims: render.Delims{Left: "{{", Right: "}}"},
  118. secureJsonPrefix: "while(1);",
  119. }
  120. engine.RouterGroup.engine = engine
  121. engine.pool.New = func() interface{} {
  122. return engine.allocateContext()
  123. }
  124. return engine
  125. }
  126. // Default returns an Engine instance with the Logger and Recovery middleware already attached.
  127. func Default() *Engine {
  128. debugPrintWARNINGDefault()
  129. engine := New()
  130. engine.Use(Logger(), Recovery())
  131. return engine
  132. }
  133. func (engine *Engine) allocateContext() *Context {
  134. return &Context{engine: engine}
  135. }
  136. // Delims sets template left and right delims and returns a Engine instance.
  137. func (engine *Engine) Delims(left, right string) *Engine {
  138. engine.delims = render.Delims{Left: left, Right: right}
  139. return engine
  140. }
  141. // SecureJsonPrefix sets the secureJsonPrefix used in Context.SecureJSON.
  142. func (engine *Engine) SecureJsonPrefix(prefix string) *Engine {
  143. engine.secureJsonPrefix = prefix
  144. return engine
  145. }
  146. // LoadHTMLGlob loads HTML files identified by glob pattern
  147. // and associates the result with HTML renderer.
  148. func (engine *Engine) LoadHTMLGlob(pattern string) {
  149. left := engine.delims.Left
  150. right := engine.delims.Right
  151. templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern))
  152. if IsDebugging() {
  153. debugPrintLoadTemplate(templ)
  154. engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims}
  155. return
  156. }
  157. engine.SetHTMLTemplate(templ)
  158. }
  159. // LoadHTMLFiles loads a slice of HTML files
  160. // and associates the result with HTML renderer.
  161. func (engine *Engine) LoadHTMLFiles(files ...string) {
  162. if IsDebugging() {
  163. engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims}
  164. return
  165. }
  166. templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...))
  167. engine.SetHTMLTemplate(templ)
  168. }
  169. // SetHTMLTemplate associate a template with HTML renderer.
  170. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  171. if len(engine.trees) > 0 {
  172. debugPrintWARNINGSetHTMLTemplate()
  173. }
  174. engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)}
  175. }
  176. // SetFuncMap sets the FuncMap used for template.FuncMap.
  177. func (engine *Engine) SetFuncMap(funcMap template.FuncMap) {
  178. engine.FuncMap = funcMap
  179. }
  180. // NoRoute adds handlers for NoRoute. It return a 404 code by default.
  181. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  182. engine.noRoute = handlers
  183. engine.rebuild404Handlers()
  184. }
  185. // NoMethod sets the handlers called when... TODO.
  186. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  187. engine.noMethod = handlers
  188. engine.rebuild405Handlers()
  189. }
  190. // Use attachs a global middleware to the router. ie. the middleware attached though Use() will be
  191. // included in the handlers chain for every single request. Even 404, 405, static files...
  192. // For example, this is the right place for a logger or error management middleware.
  193. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
  194. engine.RouterGroup.Use(middleware...)
  195. engine.rebuild404Handlers()
  196. engine.rebuild405Handlers()
  197. return engine
  198. }
  199. func (engine *Engine) rebuild404Handlers() {
  200. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  201. }
  202. func (engine *Engine) rebuild405Handlers() {
  203. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  204. }
  205. func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
  206. assert1(path[0] == '/', "path must begin with '/'")
  207. assert1(method != "", "HTTP method can not be empty")
  208. assert1(len(handlers) > 0, "there must be at least one handler")
  209. debugPrintRoute(method, path, handlers)
  210. root := engine.trees.get(method)
  211. if root == nil {
  212. root = new(node)
  213. engine.trees = append(engine.trees, methodTree{method: method, root: root})
  214. }
  215. root.addRoute(path, handlers)
  216. }
  217. // Routes returns a slice of registered routes, including some useful information, such as:
  218. // the http method, path and the handler name.
  219. func (engine *Engine) Routes() (routes RoutesInfo) {
  220. for _, tree := range engine.trees {
  221. routes = iterate("", tree.method, routes, tree.root)
  222. }
  223. return routes
  224. }
  225. func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {
  226. path += root.path
  227. if len(root.handlers) > 0 {
  228. handlerFunc := root.handlers.Last()
  229. routes = append(routes, RouteInfo{
  230. Method: method,
  231. Path: path,
  232. Handler: nameOfFunction(handlerFunc),
  233. HandlerFunc: handlerFunc,
  234. })
  235. }
  236. for _, child := range root.children {
  237. routes = iterate(path, method, routes, child)
  238. }
  239. return routes
  240. }
  241. // Run attaches the router to a http.Server and starts listening and serving HTTP requests.
  242. // It is a shortcut for http.ListenAndServe(addr, router)
  243. // Note: this method will block the calling goroutine indefinitely unless an error happens.
  244. func (engine *Engine) Run(addr ...string) (err error) {
  245. defer func() { debugPrintError(err) }()
  246. address := resolveAddress(addr)
  247. debugPrint("Listening and serving HTTP on %s\n", address)
  248. err = http.ListenAndServe(address, engine)
  249. return
  250. }
  251. // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
  252. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
  253. // Note: this method will block the calling goroutine indefinitely unless an error happens.
  254. func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) {
  255. debugPrint("Listening and serving HTTPS on %s\n", addr)
  256. defer func() { debugPrintError(err) }()
  257. err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
  258. return
  259. }
  260. // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests
  261. // through the specified unix socket (ie. a file).
  262. // Note: this method will block the calling goroutine indefinitely unless an error happens.
  263. func (engine *Engine) RunUnix(file string) (err error) {
  264. debugPrint("Listening and serving HTTP on unix:/%s", file)
  265. defer func() { debugPrintError(err) }()
  266. os.Remove(file)
  267. listener, err := net.Listen("unix", file)
  268. if err != nil {
  269. return
  270. }
  271. defer listener.Close()
  272. err = http.Serve(listener, engine)
  273. return
  274. }
  275. // ServeHTTP conforms to the http.Handler interface.
  276. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  277. c := engine.pool.Get().(*Context)
  278. c.writermem.reset(w)
  279. c.Request = req
  280. c.reset()
  281. engine.handleHTTPRequest(c)
  282. engine.pool.Put(c)
  283. }
  284. // HandleContext re-enter a context that has been rewritten.
  285. // This can be done by setting c.Request.URL.Path to your new target.
  286. // Disclaimer: You can loop yourself to death with this, use wisely.
  287. func (engine *Engine) HandleContext(c *Context) {
  288. c.reset()
  289. engine.handleHTTPRequest(c)
  290. }
  291. func (engine *Engine) handleHTTPRequest(c *Context) {
  292. httpMethod := c.Request.Method
  293. path := c.Request.URL.Path
  294. unescape := false
  295. if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {
  296. path = c.Request.URL.RawPath
  297. unescape = engine.UnescapePathValues
  298. }
  299. // Find root of the tree for the given HTTP method
  300. t := engine.trees
  301. for i, tl := 0, len(t); i < tl; i++ {
  302. if t[i].method != httpMethod {
  303. continue
  304. }
  305. root := t[i].root
  306. // Find route in tree
  307. handlers, params, tsr := root.getValue(path, c.Params, unescape)
  308. if handlers != nil {
  309. c.handlers = handlers
  310. c.Params = params
  311. c.Next()
  312. c.writermem.WriteHeaderNow()
  313. return
  314. }
  315. if httpMethod != "CONNECT" && path != "/" {
  316. if tsr && engine.RedirectTrailingSlash {
  317. redirectTrailingSlash(c)
  318. return
  319. }
  320. if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) {
  321. return
  322. }
  323. }
  324. break
  325. }
  326. if engine.HandleMethodNotAllowed {
  327. for _, tree := range engine.trees {
  328. if tree.method == httpMethod {
  329. continue
  330. }
  331. if handlers, _, _ := tree.root.getValue(path, nil, unescape); handlers != nil {
  332. c.handlers = engine.allNoMethod
  333. serveError(c, http.StatusMethodNotAllowed, default405Body)
  334. return
  335. }
  336. }
  337. }
  338. c.handlers = engine.allNoRoute
  339. serveError(c, http.StatusNotFound, default404Body)
  340. }
  341. var mimePlain = []string{MIMEPlain}
  342. func serveError(c *Context, code int, defaultMessage []byte) {
  343. c.writermem.status = code
  344. c.Next()
  345. if c.writermem.Written() {
  346. return
  347. }
  348. if c.writermem.Status() == code {
  349. c.writermem.Header()["Content-Type"] = mimePlain
  350. c.Writer.Write(defaultMessage)
  351. return
  352. }
  353. c.writermem.WriteHeaderNow()
  354. return
  355. }
  356. func redirectTrailingSlash(c *Context) {
  357. req := c.Request
  358. path := req.URL.Path
  359. code := http.StatusMovedPermanently // Permanent redirect, request with GET method
  360. if req.Method != "GET" {
  361. code = http.StatusTemporaryRedirect
  362. }
  363. req.URL.Path = path + "/"
  364. if length := len(path); length > 1 && path[length-1] == '/' {
  365. req.URL.Path = path[:length-1]
  366. }
  367. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  368. http.Redirect(c.Writer, req, req.URL.String(), code)
  369. c.writermem.WriteHeaderNow()
  370. }
  371. func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {
  372. req := c.Request
  373. path := req.URL.Path
  374. if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(path), trailingSlash); ok {
  375. code := http.StatusMovedPermanently // Permanent redirect, request with GET method
  376. if req.Method != "GET" {
  377. code = http.StatusTemporaryRedirect
  378. }
  379. req.URL.Path = string(fixedPath)
  380. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  381. http.Redirect(c.Writer, req, req.URL.String(), code)
  382. c.writermem.WriteHeaderNow()
  383. return true
  384. }
  385. return false
  386. }