gin.go 10 KB

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