gin.go 15 KB

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