gin.go 13 KB

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