gin.go 9.2 KB

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