gin.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. const Version = "v1.0rc2"
  14. var default404Body = []byte("404 page not found")
  15. var default405Body = []byte("405 method not allowed")
  16. type (
  17. HandlerFunc func(*Context)
  18. HandlersChain []HandlerFunc
  19. // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.
  20. Engine struct {
  21. RouterGroup
  22. HTMLRender render.HTMLRender
  23. allNoRoute HandlersChain
  24. allNoMethod HandlersChain
  25. noRoute HandlersChain
  26. noMethod HandlersChain
  27. pool sync.Pool
  28. trees methodTrees
  29. // Enables automatic redirection if the current route can't be matched but a
  30. // handler for the path with (without) the trailing slash exists.
  31. // For example if /foo/ is requested but a route only exists for /foo, the
  32. // client is redirected to /foo with http status code 301 for GET requests
  33. // and 307 for all other request methods.
  34. RedirectTrailingSlash bool
  35. // If enabled, the router tries to fix the current request path, if no
  36. // handle is registered for it.
  37. // First superfluous path elements like ../ or // are removed.
  38. // Afterwards the router does a case-insensitive lookup of the cleaned path.
  39. // If a handle can be found for this route, the router makes a redirection
  40. // to the corrected path with status code 301 for GET requests and 307 for
  41. // all other request methods.
  42. // For example /FOO and /..//Foo could be redirected to /foo.
  43. // RedirectTrailingSlash is independent of this option.
  44. RedirectFixedPath bool
  45. // If enabled, the router checks if another method is allowed for the
  46. // current route, if the current request can not be routed.
  47. // If this is the case, the request is answered with 'Method Not Allowed'
  48. // and HTTP status code 405.
  49. // If no other Method is allowed, the request is delegated to the NotFound
  50. // handler.
  51. HandleMethodNotAllowed bool
  52. ForwardedByClientIP bool
  53. }
  54. RouteInfo struct {
  55. Method string
  56. Path string
  57. Handler string
  58. }
  59. )
  60. func (c HandlersChain) Last() HandlerFunc {
  61. length := len(c)
  62. if length > 0 {
  63. return c[length-1]
  64. }
  65. return nil
  66. }
  67. // Returns a new blank Engine instance without any middleware attached.
  68. // The most basic configuration
  69. func New() *Engine {
  70. debugPrintWARNING()
  71. engine := &Engine{
  72. RouterGroup: RouterGroup{
  73. Handlers: nil,
  74. BasePath: "/",
  75. root: true,
  76. },
  77. RedirectTrailingSlash: true,
  78. RedirectFixedPath: false,
  79. HandleMethodNotAllowed: false,
  80. ForwardedByClientIP: true,
  81. trees: make(methodTrees, 0, 9),
  82. }
  83. engine.RouterGroup.engine = engine
  84. engine.pool.New = func() interface{} {
  85. return engine.allocateContext()
  86. }
  87. return engine
  88. }
  89. // Returns a Engine instance with the Logger and Recovery already attached.
  90. func Default() *Engine {
  91. engine := New()
  92. engine.Use(Recovery(), Logger())
  93. return engine
  94. }
  95. func (engine *Engine) allocateContext() *Context {
  96. return &Context{engine: engine}
  97. }
  98. func (engine *Engine) LoadHTMLGlob(pattern string) {
  99. if IsDebugging() {
  100. engine.HTMLRender = render.HTMLDebug{Glob: pattern}
  101. } else {
  102. templ := template.Must(template.ParseGlob(pattern))
  103. engine.SetHTMLTemplate(templ)
  104. }
  105. }
  106. func (engine *Engine) LoadHTMLFiles(files ...string) {
  107. if IsDebugging() {
  108. engine.HTMLRender = render.HTMLDebug{Files: files}
  109. } else {
  110. templ := template.Must(template.ParseFiles(files...))
  111. engine.SetHTMLTemplate(templ)
  112. }
  113. }
  114. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  115. if len(engine.trees) > 0 {
  116. debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called
  117. at initialization. ie. before any route is registered or the router is listening in a socket:
  118. router := gin.Default()
  119. router.SetHTMLTemplate(template) // << good place
  120. `)
  121. }
  122. engine.HTMLRender = render.HTMLProduction{Template: templ}
  123. }
  124. // Adds handlers for NoRoute. It return a 404 code by default.
  125. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  126. engine.noRoute = handlers
  127. engine.rebuild404Handlers()
  128. }
  129. // Sets the handlers called when... TODO
  130. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  131. engine.noMethod = handlers
  132. engine.rebuild405Handlers()
  133. }
  134. // Attachs a global middleware to the router. ie. the middlewares attached though Use() will be
  135. // included in the handlers chain for every single request. Even 404, 405, static files...
  136. // For example, this is the right place for a logger or error management middleware.
  137. func (engine *Engine) Use(middlewares ...HandlerFunc) routesInterface {
  138. engine.RouterGroup.Use(middlewares...)
  139. engine.rebuild404Handlers()
  140. engine.rebuild405Handlers()
  141. return engine
  142. }
  143. func (engine *Engine) rebuild404Handlers() {
  144. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  145. }
  146. func (engine *Engine) rebuild405Handlers() {
  147. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  148. }
  149. func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
  150. debugPrintRoute(method, path, handlers)
  151. if path[0] != '/' {
  152. panic("path must begin with '/'")
  153. }
  154. if method == "" {
  155. panic("HTTP method can not be empty")
  156. }
  157. if len(handlers) == 0 {
  158. panic("there must be at least one handler")
  159. }
  160. root := engine.trees.get(method)
  161. if root == nil {
  162. root = new(node)
  163. engine.trees = append(engine.trees, methodTree{
  164. method: method,
  165. root: root,
  166. })
  167. }
  168. root.addRoute(path, handlers)
  169. }
  170. func (engine *Engine) Routes() (routes []RouteInfo) {
  171. for _, tree := range engine.trees {
  172. routes = iterate("", tree.method, routes, tree.root)
  173. }
  174. return routes
  175. }
  176. func iterate(path, method string, routes []RouteInfo, root *node) []RouteInfo {
  177. path += root.path
  178. if len(root.handlers) > 0 {
  179. routes = append(routes, RouteInfo{
  180. Method: method,
  181. Path: path,
  182. Handler: nameOfFunction(root.handlers.Last()),
  183. })
  184. }
  185. for _, node := range root.children {
  186. routes = iterate(path, method, routes, node)
  187. }
  188. return routes
  189. }
  190. // The router is attached to a http.Server and starts listening and serving HTTP requests.
  191. // It is a shortcut for http.ListenAndServe(addr, router)
  192. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  193. func (engine *Engine) Run(addr string) (err error) {
  194. debugPrint("Listening and serving HTTP on %s\n", addr)
  195. defer func() { debugPrintError(err) }()
  196. err = http.ListenAndServe(addr, engine)
  197. return
  198. }
  199. // The router is attached to a http.Server and starts listening and serving HTTPS requests.
  200. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
  201. // Note: this method will block the calling goroutine undefinitelly 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. // The router is attached 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 undefinitelly 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.RedirectFixedPath {
  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. }