gin.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. "fmt"
  7. "github.com/gin-gonic/gin/render"
  8. "github.com/julienschmidt/httprouter"
  9. "html/template"
  10. "math"
  11. "net/http"
  12. "path"
  13. "sync"
  14. )
  15. const (
  16. AbortIndex = math.MaxInt8 / 2
  17. MIMEJSON = "application/json"
  18. MIMEHTML = "text/html"
  19. MIMEXML = "application/xml"
  20. MIMEXML2 = "text/xml"
  21. MIMEPlain = "text/plain"
  22. MIMEPOSTForm = "application/x-www-form-urlencoded"
  23. )
  24. type (
  25. HandlerFunc func(*Context)
  26. // Used internally to configure router, a RouterGroup is associated with a prefix
  27. // and an array of handlers (middlewares)
  28. RouterGroup struct {
  29. Handlers []HandlerFunc
  30. prefix string
  31. parent *RouterGroup
  32. engine *Engine
  33. }
  34. // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.
  35. Engine struct {
  36. *RouterGroup
  37. HTMLRender render.Render
  38. cache sync.Pool
  39. finalNoRoute []HandlerFunc
  40. noRoute []HandlerFunc
  41. router *httprouter.Router
  42. }
  43. )
  44. func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {
  45. c := engine.createContext(w, req, nil, engine.finalNoRoute)
  46. // set 404 by default, useful for logging
  47. c.Writer.WriteHeader(404)
  48. c.Next()
  49. if !c.Writer.Written() {
  50. if c.Writer.Status() == 404 {
  51. c.Data(-1, MIMEPlain, []byte("404 page not found"))
  52. } else {
  53. c.Writer.WriteHeaderNow()
  54. }
  55. }
  56. engine.cache.Put(c)
  57. }
  58. // Returns a new blank Engine instance without any middleware attached.
  59. // The most basic configuration
  60. func New() *Engine {
  61. engine := &Engine{}
  62. engine.RouterGroup = &RouterGroup{nil, "/", nil, engine}
  63. engine.router = httprouter.New()
  64. engine.router.NotFound = engine.handle404
  65. engine.cache.New = func() interface{} {
  66. c := &Context{Engine: engine}
  67. c.Writer = &c.writermem
  68. return c
  69. }
  70. return engine
  71. }
  72. // Returns a Engine instance with the Logger and Recovery already attached.
  73. func Default() *Engine {
  74. engine := New()
  75. engine.Use(Recovery(), Logger())
  76. return engine
  77. }
  78. func (engine *Engine) LoadHTMLGlob(pattern string) {
  79. if gin_mode == debugCode {
  80. engine.HTMLRender = render.HTMLDebug
  81. } else {
  82. templ := template.Must(template.ParseGlob(pattern))
  83. engine.SetHTMLTemplate(templ)
  84. }
  85. }
  86. func (engine *Engine) LoadHTMLFiles(files ...string) {
  87. if gin_mode == debugCode {
  88. engine.HTMLRender = render.HTMLDebug
  89. } else {
  90. templ := template.Must(template.ParseFiles(files...))
  91. engine.SetHTMLTemplate(templ)
  92. }
  93. }
  94. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  95. engine.HTMLRender = render.HTMLRender{
  96. Template: templ,
  97. }
  98. }
  99. // Adds handlers for NoRoute. It return a 404 code by default.
  100. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  101. engine.noRoute = handlers
  102. engine.finalNoRoute = engine.combineHandlers(engine.noRoute)
  103. }
  104. func (engine *Engine) Use(middlewares ...HandlerFunc) {
  105. engine.RouterGroup.Use(middlewares...)
  106. engine.finalNoRoute = engine.combineHandlers(engine.noRoute)
  107. }
  108. // ServeHTTP makes the router implement the http.Handler interface.
  109. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  110. engine.router.ServeHTTP(w, req)
  111. }
  112. func (engine *Engine) Run(addr string) {
  113. if gin_mode == debugCode {
  114. fmt.Println("[GIN-debug] Listening and serving HTTP on " + addr)
  115. }
  116. if err := http.ListenAndServe(addr, engine); err != nil {
  117. panic(err)
  118. }
  119. }
  120. func (engine *Engine) RunTLS(addr string, cert string, key string) {
  121. if gin_mode == debugCode {
  122. fmt.Println("[GIN-debug] Listening and serving HTTPS on " + addr)
  123. }
  124. if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {
  125. panic(err)
  126. }
  127. }
  128. /************************************/
  129. /********** ROUTES GROUPING *********/
  130. /************************************/
  131. // Adds middlewares to the group, see example code in github.
  132. func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
  133. group.Handlers = append(group.Handlers, middlewares...)
  134. }
  135. // Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
  136. // For example, all the routes that use a common middlware for authorization could be grouped.
  137. func (group *RouterGroup) Group(component string, handlers ...HandlerFunc) *RouterGroup {
  138. prefix := group.pathFor(component)
  139. return &RouterGroup{
  140. Handlers: group.combineHandlers(handlers),
  141. parent: group,
  142. prefix: prefix,
  143. engine: group.engine,
  144. }
  145. }
  146. func (group *RouterGroup) pathFor(p string) string {
  147. joined := path.Join(group.prefix, p)
  148. // Append a '/' if the last component had one, but only if it's not there already
  149. if len(p) > 0 && p[len(p)-1] == '/' && joined[len(joined)-1] != '/' {
  150. return joined + "/"
  151. }
  152. return joined
  153. }
  154. // Handle registers a new request handle and middlewares with the given path and method.
  155. // The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.
  156. // See the example code in github.
  157. //
  158. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  159. // functions can be used.
  160. //
  161. // This function is intended for bulk loading and to allow the usage of less
  162. // frequently used, non-standardized or custom methods (e.g. for internal
  163. // communication with a proxy).
  164. func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {
  165. p = group.pathFor(p)
  166. handlers = group.combineHandlers(handlers)
  167. if gin_mode == debugCode {
  168. nuHandlers := len(handlers)
  169. name := funcName(handlers[nuHandlers-1])
  170. fmt.Printf("[GIN-debug] %-5s %-25s --> %s (%d handlers)\n", method, p, name, nuHandlers)
  171. }
  172. group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
  173. c := group.engine.createContext(w, req, params, handlers)
  174. c.Next()
  175. c.Writer.WriteHeaderNow()
  176. group.engine.cache.Put(c)
  177. })
  178. }
  179. // POST is a shortcut for router.Handle("POST", path, handle)
  180. func (group *RouterGroup) POST(path string, handlers ...HandlerFunc) {
  181. group.Handle("POST", path, handlers)
  182. }
  183. // GET is a shortcut for router.Handle("GET", path, handle)
  184. func (group *RouterGroup) GET(path string, handlers ...HandlerFunc) {
  185. group.Handle("GET", path, handlers)
  186. }
  187. // DELETE is a shortcut for router.Handle("DELETE", path, handle)
  188. func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc) {
  189. group.Handle("DELETE", path, handlers)
  190. }
  191. // PATCH is a shortcut for router.Handle("PATCH", path, handle)
  192. func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc) {
  193. group.Handle("PATCH", path, handlers)
  194. }
  195. // PUT is a shortcut for router.Handle("PUT", path, handle)
  196. func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc) {
  197. group.Handle("PUT", path, handlers)
  198. }
  199. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
  200. func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {
  201. group.Handle("OPTIONS", path, handlers)
  202. }
  203. // HEAD is a shortcut for router.Handle("HEAD", path, handle)
  204. func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {
  205. group.Handle("HEAD", path, handlers)
  206. }
  207. // Static serves files from the given file system root.
  208. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  209. // of the Router's NotFound handler.
  210. // To use the operating system's file system implementation,
  211. // use :
  212. // router.Static("/static", "/var/www")
  213. func (group *RouterGroup) Static(p, root string) {
  214. prefix := group.pathFor(p)
  215. p = path.Join(p, "/*filepath")
  216. fileServer := http.StripPrefix(prefix, http.FileServer(http.Dir(root)))
  217. group.GET(p, func(c *Context) {
  218. fileServer.ServeHTTP(c.Writer, c.Request)
  219. })
  220. group.HEAD(p, func(c *Context) {
  221. fileServer.ServeHTTP(c.Writer, c.Request)
  222. })
  223. }
  224. func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {
  225. s := len(group.Handlers) + len(handlers)
  226. h := make([]HandlerFunc, 0, s)
  227. h = append(h, group.Handlers...)
  228. h = append(h, handlers...)
  229. return h
  230. }