gin.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. render.HTMLDebug.AddGlob(pattern)
  81. engine.HTMLRender = render.HTMLDebug
  82. } else {
  83. templ := template.Must(template.ParseGlob(pattern))
  84. engine.SetHTMLTemplate(templ)
  85. }
  86. }
  87. func (engine *Engine) LoadHTMLFiles(files ...string) {
  88. if gin_mode == debugCode {
  89. render.HTMLDebug.AddFiles(files...)
  90. engine.HTMLRender = render.HTMLDebug
  91. } else {
  92. templ := template.Must(template.ParseFiles(files...))
  93. engine.SetHTMLTemplate(templ)
  94. }
  95. }
  96. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  97. engine.HTMLRender = render.HTMLRender{
  98. Template: templ,
  99. }
  100. }
  101. // Adds handlers for NoRoute. It return a 404 code by default.
  102. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  103. engine.noRoute = handlers
  104. engine.finalNoRoute = engine.combineHandlers(engine.noRoute)
  105. }
  106. func (engine *Engine) Use(middlewares ...HandlerFunc) {
  107. engine.RouterGroup.Use(middlewares...)
  108. engine.finalNoRoute = engine.combineHandlers(engine.noRoute)
  109. }
  110. // ServeHTTP makes the router implement the http.Handler interface.
  111. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  112. engine.router.ServeHTTP(w, req)
  113. }
  114. func (engine *Engine) Run(addr string) {
  115. if gin_mode == debugCode {
  116. fmt.Println("[GIN-debug] Listening and serving HTTP on " + addr)
  117. }
  118. if err := http.ListenAndServe(addr, engine); err != nil {
  119. panic(err)
  120. }
  121. }
  122. func (engine *Engine) RunTLS(addr string, cert string, key string) {
  123. if gin_mode == debugCode {
  124. fmt.Println("[GIN-debug] Listening and serving HTTPS on " + addr)
  125. }
  126. if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {
  127. panic(err)
  128. }
  129. }
  130. /************************************/
  131. /********** ROUTES GROUPING *********/
  132. /************************************/
  133. // Adds middlewares to the group, see example code in github.
  134. func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
  135. group.Handlers = append(group.Handlers, middlewares...)
  136. }
  137. // Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
  138. // For example, all the routes that use a common middlware for authorization could be grouped.
  139. func (group *RouterGroup) Group(component string, handlers ...HandlerFunc) *RouterGroup {
  140. prefix := group.pathFor(component)
  141. return &RouterGroup{
  142. Handlers: group.combineHandlers(handlers),
  143. parent: group,
  144. prefix: prefix,
  145. engine: group.engine,
  146. }
  147. }
  148. func (group *RouterGroup) pathFor(p string) string {
  149. joined := path.Join(group.prefix, p)
  150. // Append a '/' if the last component had one, but only if it's not there already
  151. if len(p) > 0 && p[len(p)-1] == '/' && joined[len(joined)-1] != '/' {
  152. return joined + "/"
  153. }
  154. return joined
  155. }
  156. // Handle registers a new request handle and middlewares with the given path and method.
  157. // The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.
  158. // See the example code in github.
  159. //
  160. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  161. // functions can be used.
  162. //
  163. // This function is intended for bulk loading and to allow the usage of less
  164. // frequently used, non-standardized or custom methods (e.g. for internal
  165. // communication with a proxy).
  166. func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {
  167. p = group.pathFor(p)
  168. handlers = group.combineHandlers(handlers)
  169. if gin_mode == debugCode {
  170. nuHandlers := len(handlers)
  171. name := funcName(handlers[nuHandlers-1])
  172. fmt.Printf("[GIN-debug] %-5s %-25s --> %s (%d handlers)\n", method, p, name, nuHandlers)
  173. }
  174. group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
  175. c := group.engine.createContext(w, req, params, handlers)
  176. c.Next()
  177. c.Writer.WriteHeaderNow()
  178. group.engine.cache.Put(c)
  179. })
  180. }
  181. // POST is a shortcut for router.Handle("POST", path, handle)
  182. func (group *RouterGroup) POST(path string, handlers ...HandlerFunc) {
  183. group.Handle("POST", path, handlers)
  184. }
  185. // GET is a shortcut for router.Handle("GET", path, handle)
  186. func (group *RouterGroup) GET(path string, handlers ...HandlerFunc) {
  187. group.Handle("GET", path, handlers)
  188. }
  189. // DELETE is a shortcut for router.Handle("DELETE", path, handle)
  190. func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc) {
  191. group.Handle("DELETE", path, handlers)
  192. }
  193. // PATCH is a shortcut for router.Handle("PATCH", path, handle)
  194. func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc) {
  195. group.Handle("PATCH", path, handlers)
  196. }
  197. // PUT is a shortcut for router.Handle("PUT", path, handle)
  198. func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc) {
  199. group.Handle("PUT", path, handlers)
  200. }
  201. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
  202. func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {
  203. group.Handle("OPTIONS", path, handlers)
  204. }
  205. // HEAD is a shortcut for router.Handle("HEAD", path, handle)
  206. func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {
  207. group.Handle("HEAD", path, handlers)
  208. }
  209. // Static serves files from the given file system root.
  210. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  211. // of the Router's NotFound handler.
  212. // To use the operating system's file system implementation,
  213. // use :
  214. // router.Static("/static", "/var/www")
  215. func (group *RouterGroup) Static(p, root string) {
  216. prefix := group.pathFor(p)
  217. p = path.Join(p, "/*filepath")
  218. fileServer := http.StripPrefix(prefix, http.FileServer(http.Dir(root)))
  219. group.GET(p, func(c *Context) {
  220. fileServer.ServeHTTP(c.Writer, c.Request)
  221. })
  222. group.HEAD(p, func(c *Context) {
  223. fileServer.ServeHTTP(c.Writer, c.Request)
  224. })
  225. }
  226. func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {
  227. s := len(group.Handlers) + len(handlers)
  228. h := make([]HandlerFunc, 0, s)
  229. h = append(h, group.Handlers...)
  230. h = append(h, handlers...)
  231. return h
  232. }