gin.go 6.8 KB

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