gin.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. // 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. // 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. // Sets the handlers called when... TODO
  136. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  137. engine.noMethod = handlers
  138. engine.rebuild405Handlers()
  139. }
  140. // 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. debugPrintRoute(method, path, handlers)
  157. if path[0] != '/' {
  158. panic("path must begin with '/'")
  159. }
  160. if method == "" {
  161. panic("HTTP method can not be empty")
  162. }
  163. if len(handlers) == 0 {
  164. panic("there must be at least one handler")
  165. }
  166. root := engine.trees.get(method)
  167. if root == nil {
  168. root = new(node)
  169. engine.trees = append(engine.trees, methodTree{
  170. method: method,
  171. root: root,
  172. })
  173. }
  174. root.addRoute(path, handlers)
  175. }
  176. // Routes returns a slice of registered routes, including some useful information, such as:
  177. // the http method, path and the handler name.
  178. func (engine *Engine) Routes() (routes RoutesInfo) {
  179. for _, tree := range engine.trees {
  180. routes = iterate("", tree.method, routes, tree.root)
  181. }
  182. return routes
  183. }
  184. func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {
  185. path += root.path
  186. if len(root.handlers) > 0 {
  187. routes = append(routes, RouteInfo{
  188. Method: method,
  189. Path: path,
  190. Handler: nameOfFunction(root.handlers.Last()),
  191. })
  192. }
  193. for _, child := range root.children {
  194. routes = iterate(path, method, routes, child)
  195. }
  196. return routes
  197. }
  198. // Run attaches the router to a http.Server and starts listening and serving HTTP requests.
  199. // It is a shortcut for http.ListenAndServe(addr, router)
  200. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  201. func (engine *Engine) Run(addr ...string) (err error) {
  202. defer func() { debugPrintError(err) }()
  203. address := resolveAddress(addr)
  204. debugPrint("Listening and serving HTTP on %s\n", address)
  205. err = http.ListenAndServe(address, engine)
  206. return
  207. }
  208. // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
  209. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
  210. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  211. func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {
  212. debugPrint("Listening and serving HTTPS on %s\n", addr)
  213. defer func() { debugPrintError(err) }()
  214. err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
  215. return
  216. }
  217. // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests
  218. // through the specified unix socket (ie. a file).
  219. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  220. func (engine *Engine) RunUnix(file string) (err error) {
  221. debugPrint("Listening and serving HTTP on unix:/%s", file)
  222. defer func() { debugPrintError(err) }()
  223. os.Remove(file)
  224. listener, err := net.Listen("unix", file)
  225. if err != nil {
  226. return
  227. }
  228. defer listener.Close()
  229. err = http.Serve(listener, engine)
  230. return
  231. }
  232. // Conforms to the http.Handler interface.
  233. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  234. c := engine.pool.Get().(*Context)
  235. c.writermem.reset(w)
  236. c.Request = req
  237. c.reset()
  238. engine.handleHTTPRequest(c)
  239. engine.pool.Put(c)
  240. }
  241. func (engine *Engine) handleHTTPRequest(context *Context) {
  242. httpMethod := context.Request.Method
  243. path := context.Request.URL.Path
  244. // Find root of the tree for the given HTTP method
  245. t := engine.trees
  246. for i, tl := 0, len(t); i < tl; i++ {
  247. if t[i].method == httpMethod {
  248. root := t[i].root
  249. // Find route in tree
  250. handlers, params, tsr := root.getValue(path, context.Params)
  251. if handlers != nil {
  252. context.handlers = handlers
  253. context.Params = params
  254. context.Next()
  255. context.writermem.WriteHeaderNow()
  256. return
  257. } else if httpMethod != "CONNECT" && path != "/" {
  258. if tsr && engine.RedirectTrailingSlash {
  259. redirectTrailingSlash(context)
  260. return
  261. }
  262. if engine.RedirectFixedPath && redirectFixedPath(context, root, engine.RedirectFixedPath) {
  263. return
  264. }
  265. }
  266. break
  267. }
  268. }
  269. // TODO: unit test
  270. if engine.HandleMethodNotAllowed {
  271. for _, tree := range engine.trees {
  272. if tree.method != httpMethod {
  273. if handlers, _, _ := tree.root.getValue(path, nil); handlers != nil {
  274. context.handlers = engine.allNoMethod
  275. serveError(context, 405, default405Body)
  276. return
  277. }
  278. }
  279. }
  280. }
  281. context.handlers = engine.allNoRoute
  282. serveError(context, 404, default404Body)
  283. }
  284. var mimePlain = []string{MIMEPlain}
  285. func serveError(c *Context, code int, defaultMessage []byte) {
  286. c.writermem.status = code
  287. c.Next()
  288. if !c.writermem.Written() {
  289. if c.writermem.Status() == code {
  290. c.writermem.Header()["Content-Type"] = mimePlain
  291. c.Writer.Write(defaultMessage)
  292. } else {
  293. c.writermem.WriteHeaderNow()
  294. }
  295. }
  296. }
  297. func redirectTrailingSlash(c *Context) {
  298. req := c.Request
  299. path := req.URL.Path
  300. code := 301 // Permanent redirect, request with GET method
  301. if req.Method != "GET" {
  302. code = 307
  303. }
  304. if len(path) > 1 && path[len(path)-1] == '/' {
  305. req.URL.Path = path[:len(path)-1]
  306. } else {
  307. req.URL.Path = path + "/"
  308. }
  309. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  310. http.Redirect(c.Writer, req, req.URL.String(), code)
  311. c.writermem.WriteHeaderNow()
  312. }
  313. func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {
  314. req := c.Request
  315. path := req.URL.Path
  316. fixedPath, found := root.findCaseInsensitivePath(
  317. cleanPath(path),
  318. trailingSlash,
  319. )
  320. if found {
  321. code := 301 // Permanent redirect, request with GET method
  322. if req.Method != "GET" {
  323. code = 307
  324. }
  325. req.URL.Path = string(fixedPath)
  326. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  327. http.Redirect(c.Writer, req, req.URL.String(), code)
  328. c.writermem.WriteHeaderNow()
  329. return true
  330. }
  331. return false
  332. }