gin.go 7.6 KB

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