gin.go 12 KB

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