gin.go 14 KB

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