gin.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. package gin
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "github.com/gin-gonic/gin/binding"
  8. "github.com/gin-gonic/gin/render"
  9. "github.com/julienschmidt/httprouter"
  10. "html/template"
  11. "log"
  12. "math"
  13. "net/http"
  14. "path"
  15. "sync"
  16. )
  17. const (
  18. AbortIndex = math.MaxInt8 / 2
  19. MIMEJSON = "application/json"
  20. MIMEHTML = "text/html"
  21. MIMEXML = "application/xml"
  22. MIMEXML2 = "text/xml"
  23. MIMEPlain = "text/plain"
  24. MIMEPOSTForm = "application/x-www-form-urlencoded"
  25. )
  26. const (
  27. ErrorTypeInternal = 1 << iota
  28. ErrorTypeExternal = 1 << iota
  29. ErrorTypeAll = 0xffffffff
  30. )
  31. type (
  32. HandlerFunc func(*Context)
  33. H map[string]interface{}
  34. // Used internally to collect errors that occurred during an http request.
  35. errorMsg struct {
  36. Err string `json:"error"`
  37. Type uint32 `json:"-"`
  38. Meta interface{} `json:"meta"`
  39. }
  40. errorMsgs []errorMsg
  41. // Context is the most important part of gin. It allows us to pass variables between middleware,
  42. // manage the flow, validate the JSON of a request and render a JSON response for example.
  43. Context struct {
  44. Request *http.Request
  45. Writer ResponseWriter
  46. Keys map[string]interface{}
  47. Errors errorMsgs
  48. Params httprouter.Params
  49. Engine *Engine
  50. handlers []HandlerFunc
  51. index int8
  52. }
  53. // Used internally to configure router, a RouterGroup is associated with a prefix
  54. // and an array of handlers (middlewares)
  55. RouterGroup struct {
  56. Handlers []HandlerFunc
  57. prefix string
  58. parent *RouterGroup
  59. engine *Engine
  60. }
  61. // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.
  62. Engine struct {
  63. *RouterGroup
  64. HTMLRender render.Render
  65. cache sync.Pool
  66. handlers404 []HandlerFunc
  67. router *httprouter.Router
  68. }
  69. )
  70. // Allows type H to be used with xml.Marshal
  71. func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  72. start.Name = xml.Name{
  73. Space: "",
  74. Local: "map",
  75. }
  76. if err := e.EncodeToken(start); err != nil {
  77. return err
  78. }
  79. for key, value := range h {
  80. elem := xml.StartElement{
  81. Name: xml.Name{Space: "", Local: key},
  82. Attr: []xml.Attr{},
  83. }
  84. if err := e.EncodeElement(value, elem); err != nil {
  85. return err
  86. }
  87. }
  88. if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil {
  89. return err
  90. }
  91. return nil
  92. }
  93. func (a errorMsgs) ByType(typ uint32) errorMsgs {
  94. if len(a) == 0 {
  95. return a
  96. }
  97. result := make(errorMsgs, 0, len(a))
  98. for _, msg := range a {
  99. if msg.Type&typ > 0 {
  100. result = append(result, msg)
  101. }
  102. }
  103. return result
  104. }
  105. func (a errorMsgs) String() string {
  106. if len(a) == 0 {
  107. return ""
  108. }
  109. var buffer bytes.Buffer
  110. for i, msg := range a {
  111. text := fmt.Sprintf("Error #%02d: %s \n Meta: %v\n", (i + 1), msg.Err, msg.Meta)
  112. buffer.WriteString(text)
  113. }
  114. return buffer.String()
  115. }
  116. // Returns a new blank Engine instance without any middleware attached.
  117. // The most basic configuration
  118. func New() *Engine {
  119. engine := &Engine{}
  120. engine.RouterGroup = &RouterGroup{nil, "/", nil, engine}
  121. engine.router = httprouter.New()
  122. engine.router.NotFound = engine.handle404
  123. engine.cache.New = func() interface{} {
  124. return &Context{Engine: engine, Writer: &responseWriter{}}
  125. }
  126. return engine
  127. }
  128. // Returns a Engine instance with the Logger and Recovery already attached.
  129. func Default() *Engine {
  130. engine := New()
  131. engine.Use(Recovery(), Logger())
  132. return engine
  133. }
  134. func (engine *Engine) LoadHTMLGlob(pattern string) {
  135. templ := template.Must(template.ParseGlob(pattern))
  136. engine.SetHTTPTemplate(templ)
  137. }
  138. func (engine *Engine) LoadHTMLFiles(files ...string) {
  139. templ := template.Must(template.ParseFiles(files...))
  140. engine.SetHTTPTemplate(templ)
  141. }
  142. func (engine *Engine) SetHTTPTemplate(templ *template.Template) {
  143. engine.HTMLRender = render.HTMLRender{
  144. Template: templ,
  145. }
  146. }
  147. // Adds handlers for NotFound. It return a 404 code by default.
  148. func (engine *Engine) NotFound404(handlers ...HandlerFunc) {
  149. engine.handlers404 = handlers
  150. }
  151. func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {
  152. handlers := engine.combineHandlers(engine.handlers404)
  153. c := engine.createContext(w, req, nil, handlers)
  154. c.Writer.setStatus(404)
  155. c.Next()
  156. if !c.Writer.Written() {
  157. c.Data(404, MIMEPlain, []byte("404 page not found"))
  158. }
  159. engine.cache.Put(c)
  160. }
  161. // ServeHTTP makes the router implement the http.Handler interface.
  162. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  163. engine.router.ServeHTTP(w, req)
  164. }
  165. func (engine *Engine) Run(addr string) {
  166. if err := http.ListenAndServe(addr, engine); err != nil {
  167. panic(err)
  168. }
  169. }
  170. func (engine *Engine) RunTLS(addr string, cert string, key string) {
  171. if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {
  172. panic(err)
  173. }
  174. }
  175. /************************************/
  176. /********** ROUTES GROUPING *********/
  177. /************************************/
  178. func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
  179. c := engine.cache.Get().(*Context)
  180. c.Writer.reset(w)
  181. c.Request = req
  182. c.Params = params
  183. c.handlers = handlers
  184. c.Keys = nil
  185. c.index = -1
  186. return c
  187. }
  188. // Adds middlewares to the group, see example code in github.
  189. func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
  190. group.Handlers = append(group.Handlers, middlewares...)
  191. }
  192. func joinGroupPath(elems ...string) string {
  193. joined := path.Join(elems...)
  194. lastComponent := elems[len(elems)-1]
  195. // Append a '/' if the last component had one, but only if it's not there already
  196. if len(lastComponent) > 0 && lastComponent[len(lastComponent)-1] == '/' && joined[len(joined)-1] != '/' {
  197. return joined + "/"
  198. }
  199. return joined
  200. }
  201. // Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
  202. // For example, all the routes that use a common middlware for authorization could be grouped.
  203. func (group *RouterGroup) Group(component string, handlers ...HandlerFunc) *RouterGroup {
  204. prefix := joinGroupPath(group.prefix, component)
  205. return &RouterGroup{
  206. Handlers: group.combineHandlers(handlers),
  207. parent: group,
  208. prefix: prefix,
  209. engine: group.engine,
  210. }
  211. }
  212. // Handle registers a new request handle and middlewares with the given path and method.
  213. // The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.
  214. // See the example code in github.
  215. //
  216. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  217. // functions can be used.
  218. //
  219. // This function is intended for bulk loading and to allow the usage of less
  220. // frequently used, non-standardized or custom methods (e.g. for internal
  221. // communication with a proxy).
  222. func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {
  223. p = joinGroupPath(group.prefix, p)
  224. handlers = group.combineHandlers(handlers)
  225. group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
  226. c := group.engine.createContext(w, req, params, handlers)
  227. c.Next()
  228. group.engine.cache.Put(c)
  229. })
  230. }
  231. // POST is a shortcut for router.Handle("POST", path, handle)
  232. func (group *RouterGroup) POST(path string, handlers ...HandlerFunc) {
  233. group.Handle("POST", path, handlers)
  234. }
  235. // GET is a shortcut for router.Handle("GET", path, handle)
  236. func (group *RouterGroup) GET(path string, handlers ...HandlerFunc) {
  237. group.Handle("GET", path, handlers)
  238. }
  239. // DELETE is a shortcut for router.Handle("DELETE", path, handle)
  240. func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc) {
  241. group.Handle("DELETE", path, handlers)
  242. }
  243. // PATCH is a shortcut for router.Handle("PATCH", path, handle)
  244. func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc) {
  245. group.Handle("PATCH", path, handlers)
  246. }
  247. // PUT is a shortcut for router.Handle("PUT", path, handle)
  248. func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc) {
  249. group.Handle("PUT", path, handlers)
  250. }
  251. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
  252. func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {
  253. group.Handle("OPTIONS", path, handlers)
  254. }
  255. // HEAD is a shortcut for router.Handle("HEAD", path, handle)
  256. func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {
  257. group.Handle("HEAD", path, handlers)
  258. }
  259. // Static serves files from the given file system root.
  260. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  261. // of the Router's NotFound handler.
  262. // To use the operating system's file system implementation,
  263. // use :
  264. // router.Static("/static", "/var/www")
  265. func (group *RouterGroup) Static(p, root string) {
  266. p = path.Join(p, "/*filepath")
  267. fileServer := http.FileServer(http.Dir(root))
  268. group.GET(p, func(c *Context) {
  269. original := c.Request.URL.Path
  270. c.Request.URL.Path = c.Params.ByName("filepath")
  271. fileServer.ServeHTTP(c.Writer, c.Request)
  272. c.Request.URL.Path = original
  273. })
  274. }
  275. func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {
  276. s := len(group.Handlers) + len(handlers)
  277. h := make([]HandlerFunc, 0, s)
  278. h = append(h, group.Handlers...)
  279. h = append(h, handlers...)
  280. return h
  281. }
  282. /************************************/
  283. /****** FLOW AND ERROR MANAGEMENT****/
  284. /************************************/
  285. func (c *Context) Copy() *Context {
  286. var cp Context = *c
  287. cp.index = AbortIndex
  288. cp.handlers = nil
  289. return &cp
  290. }
  291. // Next should be used only in the middlewares.
  292. // It executes the pending handlers in the chain inside the calling handler.
  293. // See example in github.
  294. func (c *Context) Next() {
  295. c.index++
  296. s := int8(len(c.handlers))
  297. for ; c.index < s; c.index++ {
  298. c.handlers[c.index](c)
  299. }
  300. }
  301. // Forces the system to do not continue calling the pending handlers.
  302. // For example, the first handler checks if the request is authorized. If it's not, context.Abort(401) should be called.
  303. // The rest of pending handlers would never be called for that request.
  304. func (c *Context) Abort(code int) {
  305. if code >= 0 {
  306. c.Writer.WriteHeader(code)
  307. }
  308. c.index = AbortIndex
  309. }
  310. // Fail is the same as Abort plus an error message.
  311. // Calling `context.Fail(500, err)` is equivalent to:
  312. // ```
  313. // context.Error("Operation aborted", err)
  314. // context.Abort(500)
  315. // ```
  316. func (c *Context) Fail(code int, err error) {
  317. c.Error(err, "Operation aborted")
  318. c.Abort(code)
  319. }
  320. func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {
  321. c.Errors = append(c.Errors, errorMsg{
  322. Err: err.Error(),
  323. Type: typ,
  324. Meta: meta,
  325. })
  326. }
  327. // Attaches an error to the current context. The error is pushed to a list of errors.
  328. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  329. // A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response.
  330. func (c *Context) Error(err error, meta interface{}) {
  331. c.ErrorTyped(err, ErrorTypeExternal, meta)
  332. }
  333. func (c *Context) LastError() error {
  334. s := len(c.Errors)
  335. if s > 0 {
  336. return errors.New(c.Errors[s-1].Err)
  337. } else {
  338. return nil
  339. }
  340. }
  341. /************************************/
  342. /******** METADATA MANAGEMENT********/
  343. /************************************/
  344. // Sets a new pair key/value just for the specified context.
  345. // It also lazy initializes the hashmap.
  346. func (c *Context) Set(key string, item interface{}) {
  347. if c.Keys == nil {
  348. c.Keys = make(map[string]interface{})
  349. }
  350. c.Keys[key] = item
  351. }
  352. // Get returns the value for the given key or an error if the key does not exist.
  353. func (c *Context) Get(key string) (interface{}, error) {
  354. if c.Keys != nil {
  355. item, ok := c.Keys[key]
  356. if ok {
  357. return item, nil
  358. }
  359. }
  360. return nil, errors.New("Key does not exist.")
  361. }
  362. // MustGet returns the value for the given key or panics if the value doesn't exist.
  363. func (c *Context) MustGet(key string) interface{} {
  364. value, err := c.Get(key)
  365. if err != nil || value == nil {
  366. log.Panicf("Key %s doesn't exist", key)
  367. }
  368. return value
  369. }
  370. /************************************/
  371. /******** ENCOGING MANAGEMENT********/
  372. /************************************/
  373. func filterFlags(content string) string {
  374. for i, a := range content {
  375. if a == ' ' || a == ';' {
  376. return content[:i]
  377. }
  378. }
  379. return content
  380. }
  381. // This function checks the Content-Type to select a binding engine automatically,
  382. // Depending the "Content-Type" header different bindings are used:
  383. // "application/json" --> JSON binding
  384. // "application/xml" --> XML binding
  385. // else --> returns an error
  386. // if Parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer.Like ParseBody() but this method also writes a 400 error if the json is not valid.
  387. func (c *Context) Bind(obj interface{}) bool {
  388. var b binding.Binding
  389. ctype := filterFlags(c.Request.Header.Get("Content-Type"))
  390. switch {
  391. case c.Request.Method == "GET" || ctype == MIMEPOSTForm:
  392. b = binding.Form
  393. case ctype == MIMEJSON:
  394. b = binding.JSON
  395. case ctype == MIMEXML || ctype == MIMEXML2:
  396. b = binding.XML
  397. default:
  398. c.Fail(400, errors.New("unknown content-type: "+ctype))
  399. return false
  400. }
  401. return c.BindWith(obj, b)
  402. }
  403. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  404. if err := b.Bind(c.Request, obj); err != nil {
  405. c.Fail(400, err)
  406. return false
  407. }
  408. return true
  409. }
  410. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  411. if err := render.Render(c.Writer, code, obj...); err != nil {
  412. c.ErrorTyped(err, ErrorTypeInternal, obj)
  413. c.Abort(500)
  414. }
  415. }
  416. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  417. // It also sets the Content-Type as "application/json".
  418. func (c *Context) JSON(code int, obj interface{}) {
  419. c.Render(code, render.JSON, obj)
  420. }
  421. // Serializes the given struct as XML into the response body in a fast and efficient way.
  422. // It also sets the Content-Type as "application/xml".
  423. func (c *Context) XML(code int, obj interface{}) {
  424. c.Render(code, render.XML, obj)
  425. }
  426. // Renders the HTTP template specified by its file name.
  427. // It also updates the HTTP code and sets the Content-Type as "text/html".
  428. // See http://golang.org/doc/articles/wiki/
  429. func (c *Context) HTML(code int, name string, obj interface{}) {
  430. c.Render(code, c.Engine.HTMLRender, name, obj)
  431. }
  432. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  433. func (c *Context) String(code int, format string, values ...interface{}) {
  434. c.Render(code, render.Plain, format, values)
  435. }
  436. // Writes some data into the body stream and updates the HTTP code.
  437. func (c *Context) Data(code int, contentType string, data []byte) {
  438. if len(contentType) > 0 {
  439. c.Writer.Header().Set("Content-Type", contentType)
  440. }
  441. if code >= 0 {
  442. c.Writer.WriteHeader(code)
  443. }
  444. c.Writer.Write(data)
  445. }