gin.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. )
  55. // Returns a new blank Engine instance without any middleware attached.
  56. // The most basic configuration
  57. func New() *Engine {
  58. debugPrintWARNING()
  59. engine := &Engine{
  60. RouterGroup: RouterGroup{
  61. Handlers: nil,
  62. BasePath: "/",
  63. root: true,
  64. },
  65. RedirectTrailingSlash: true,
  66. RedirectFixedPath: false,
  67. HandleMethodNotAllowed: false,
  68. ForwardedByClientIP: true,
  69. trees: make(methodTrees, 0, 9),
  70. }
  71. engine.RouterGroup.engine = engine
  72. engine.pool.New = func() interface{} {
  73. return engine.allocateContext()
  74. }
  75. return engine
  76. }
  77. // Returns a Engine instance with the Logger and Recovery already attached.
  78. func Default() *Engine {
  79. engine := New()
  80. engine.Use(Recovery(), Logger())
  81. return engine
  82. }
  83. func (engine *Engine) allocateContext() *Context {
  84. return &Context{engine: engine}
  85. }
  86. func (engine *Engine) LoadHTMLGlob(pattern string) {
  87. if IsDebugging() {
  88. engine.HTMLRender = render.HTMLDebug{Glob: pattern}
  89. } else {
  90. templ := template.Must(template.ParseGlob(pattern))
  91. engine.SetHTMLTemplate(templ)
  92. }
  93. }
  94. func (engine *Engine) LoadHTMLFiles(files ...string) {
  95. if IsDebugging() {
  96. engine.HTMLRender = render.HTMLDebug{Files: files}
  97. } else {
  98. templ := template.Must(template.ParseFiles(files...))
  99. engine.SetHTMLTemplate(templ)
  100. }
  101. }
  102. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  103. if len(engine.trees) > 0 {
  104. debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called
  105. at initialization. ie. before any route is registered or the router is listening in a socket:
  106. router := gin.Default()
  107. router.SetHTMLTemplate(template) // << good place
  108. `)
  109. }
  110. engine.HTMLRender = render.HTMLProduction{Template: templ}
  111. }
  112. // Adds handlers for NoRoute. It return a 404 code by default.
  113. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  114. engine.noRoute = handlers
  115. engine.rebuild404Handlers()
  116. }
  117. // Sets the handlers called when... TODO
  118. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  119. engine.noMethod = handlers
  120. engine.rebuild405Handlers()
  121. }
  122. // Attachs a global middleware to the router. ie. the middlewares attached though Use() will be
  123. // included in the handlers chain for every single request. Even 404, 405, static files...
  124. // For example, this is the right place for a logger or error management middleware.
  125. func (engine *Engine) Use(middlewares ...HandlerFunc) routesInterface {
  126. engine.RouterGroup.Use(middlewares...)
  127. engine.rebuild404Handlers()
  128. engine.rebuild405Handlers()
  129. return engine
  130. }
  131. func (engine *Engine) rebuild404Handlers() {
  132. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  133. }
  134. func (engine *Engine) rebuild405Handlers() {
  135. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  136. }
  137. func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
  138. debugPrintRoute(method, path, handlers)
  139. if path[0] != '/' {
  140. panic("path must begin with '/'")
  141. }
  142. if method == "" {
  143. panic("HTTP method can not be empty")
  144. }
  145. if len(handlers) == 0 {
  146. panic("there must be at least one handler")
  147. }
  148. root := engine.trees.get(method)
  149. if root == nil {
  150. root = new(node)
  151. engine.trees = append(engine.trees, methodTree{
  152. method: method,
  153. root: root,
  154. })
  155. }
  156. root.addRoute(path, handlers)
  157. }
  158. // The router is attached to a http.Server and starts listening and serving HTTP requests.
  159. // It is a shortcut for http.ListenAndServe(addr, router)
  160. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  161. func (engine *Engine) Run(addr string) (err error) {
  162. debugPrint("Listening and serving HTTP on %s\n", addr)
  163. defer func() { debugPrintError(err) }()
  164. err = http.ListenAndServe(addr, engine)
  165. return
  166. }
  167. // The router is attached to a http.Server and starts listening and serving HTTPS requests.
  168. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
  169. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  170. func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {
  171. debugPrint("Listening and serving HTTPS on %s\n", addr)
  172. defer func() { debugPrintError(err) }()
  173. err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
  174. return
  175. }
  176. // The router is attached to a http.Server and starts listening and serving HTTP requests
  177. // through the specified unix socket (ie. a file)
  178. // Note: this method will block the calling goroutine undefinitelly unless an error happens.
  179. func (engine *Engine) RunUnix(file string) (err error) {
  180. debugPrint("Listening and serving HTTP on unix:/%s", file)
  181. defer func() { debugPrintError(err) }()
  182. os.Remove(file)
  183. listener, err := net.Listen("unix", file)
  184. if err != nil {
  185. return
  186. }
  187. defer listener.Close()
  188. err = http.Serve(listener, engine)
  189. return
  190. }
  191. // Conforms to the http.Handler interface.
  192. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  193. c := engine.pool.Get().(*Context)
  194. c.writermem.reset(w)
  195. c.Request = req
  196. c.reset()
  197. engine.handleHTTPRequest(c)
  198. engine.pool.Put(c)
  199. }
  200. func (engine *Engine) handleHTTPRequest(context *Context) {
  201. httpMethod := context.Request.Method
  202. path := context.Request.URL.Path
  203. // Find root of the tree for the given HTTP method
  204. t := engine.trees
  205. for i, tl := 0, len(t); i < tl; i++ {
  206. if t[i].method == httpMethod {
  207. root := t[i].root
  208. // Find route in tree
  209. handlers, params, tsr := root.getValue(path, context.Params)
  210. if handlers != nil {
  211. context.handlers = handlers
  212. context.Params = params
  213. context.Next()
  214. context.writermem.WriteHeaderNow()
  215. return
  216. } else if httpMethod != "CONNECT" && path != "/" {
  217. if tsr && engine.RedirectFixedPath {
  218. redirectTrailingSlash(context)
  219. return
  220. }
  221. if engine.RedirectFixedPath && redirectFixedPath(context, root, engine.RedirectFixedPath) {
  222. return
  223. }
  224. }
  225. break
  226. }
  227. }
  228. // TODO: unit test
  229. if engine.HandleMethodNotAllowed {
  230. for _, tree := range engine.trees {
  231. if tree.method != httpMethod {
  232. if handlers, _, _ := tree.root.getValue(path, nil); handlers != nil {
  233. context.handlers = engine.allNoMethod
  234. serveError(context, 405, default405Body)
  235. return
  236. }
  237. }
  238. }
  239. }
  240. context.handlers = engine.allNoRoute
  241. serveError(context, 404, default404Body)
  242. }
  243. var mimePlain = []string{MIMEPlain}
  244. func serveError(c *Context, code int, defaultMessage []byte) {
  245. c.writermem.status = code
  246. c.Next()
  247. if !c.writermem.Written() {
  248. if c.writermem.Status() == code {
  249. c.writermem.Header()["Content-Type"] = mimePlain
  250. c.Writer.Write(defaultMessage)
  251. } else {
  252. c.writermem.WriteHeaderNow()
  253. }
  254. }
  255. }
  256. func redirectTrailingSlash(c *Context) {
  257. req := c.Request
  258. path := req.URL.Path
  259. code := 301 // Permanent redirect, request with GET method
  260. if req.Method != "GET" {
  261. code = 307
  262. }
  263. if len(path) > 1 && path[len(path)-1] == '/' {
  264. req.URL.Path = path[:len(path)-1]
  265. } else {
  266. req.URL.Path = path + "/"
  267. }
  268. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  269. http.Redirect(c.Writer, req, req.URL.String(), code)
  270. c.writermem.WriteHeaderNow()
  271. }
  272. func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {
  273. req := c.Request
  274. path := req.URL.Path
  275. fixedPath, found := root.findCaseInsensitivePath(
  276. cleanPath(path),
  277. trailingSlash,
  278. )
  279. if found {
  280. code := 301 // Permanent redirect, request with GET method
  281. if req.Method != "GET" {
  282. code = 307
  283. }
  284. req.URL.Path = string(fixedPath)
  285. debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
  286. http.Redirect(c.Writer, req, req.URL.String(), code)
  287. c.writermem.WriteHeaderNow()
  288. return true
  289. }
  290. return false
  291. }