gin.go 7.1 KB

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