gin.go 12 KB

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