gin.go 12 KB

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