gin.go 11 KB

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