gin.go 11 KB

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