gin.go 13 KB

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