gin.go 7.0 KB

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