gin.go 9.7 KB

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