gin.go 14 KB

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