gin.go 7.7 KB

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