gin.go 11 KB

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