gin.go 14 KB

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