gin.go 13 KB

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