gin.go 9.2 KB

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