context.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "github.com/gin-gonic/gin/binding"
  10. "github.com/gin-gonic/gin/render"
  11. "github.com/julienschmidt/httprouter"
  12. "log"
  13. "net/http"
  14. )
  15. const (
  16. ErrorTypeInternal = 1 << iota
  17. ErrorTypeExternal = 1 << iota
  18. ErrorTypeAll = 0xffffffff
  19. )
  20. // Used internally to collect errors that occurred during an http request.
  21. type errorMsg struct {
  22. Err string `json:"error"`
  23. Type uint32 `json:"-"`
  24. Meta interface{} `json:"meta"`
  25. }
  26. type errorMsgs []errorMsg
  27. func (a errorMsgs) ByType(typ uint32) errorMsgs {
  28. if len(a) == 0 {
  29. return a
  30. }
  31. result := make(errorMsgs, 0, len(a))
  32. for _, msg := range a {
  33. if msg.Type&typ > 0 {
  34. result = append(result, msg)
  35. }
  36. }
  37. return result
  38. }
  39. func (a errorMsgs) String() string {
  40. if len(a) == 0 {
  41. return ""
  42. }
  43. var buffer bytes.Buffer
  44. for i, msg := range a {
  45. text := fmt.Sprintf("Error #%02d: %s \n Meta: %v\n", (i + 1), msg.Err, msg.Meta)
  46. buffer.WriteString(text)
  47. }
  48. return buffer.String()
  49. }
  50. // Context is the most important part of gin. It allows us to pass variables between middleware,
  51. // manage the flow, validate the JSON of a request and render a JSON response for example.
  52. type Context struct {
  53. writermem responseWriter
  54. Request *http.Request
  55. Writer ResponseWriter
  56. Keys map[string]interface{}
  57. Errors errorMsgs
  58. Params httprouter.Params
  59. Engine *Engine
  60. handlers []HandlerFunc
  61. index int8
  62. }
  63. /************************************/
  64. /********** ROUTES GROUPING *********/
  65. /************************************/
  66. func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
  67. c := engine.cache.Get().(*Context)
  68. c.writermem.reset(w)
  69. c.Request = req
  70. c.Params = params
  71. c.handlers = handlers
  72. c.Keys = nil
  73. c.index = -1
  74. c.Errors = c.Errors[0:0]
  75. return c
  76. }
  77. /************************************/
  78. /****** FLOW AND ERROR MANAGEMENT****/
  79. /************************************/
  80. func (c *Context) Copy() *Context {
  81. var cp Context = *c
  82. cp.index = AbortIndex
  83. cp.handlers = nil
  84. return &cp
  85. }
  86. // Next should be used only in the middlewares.
  87. // It executes the pending handlers in the chain inside the calling handler.
  88. // See example in github.
  89. func (c *Context) Next() {
  90. c.index++
  91. s := int8(len(c.handlers))
  92. for ; c.index < s; c.index++ {
  93. c.handlers[c.index](c)
  94. }
  95. }
  96. // Forces the system to do not continue calling the pending handlers.
  97. // For example, the first handler checks if the request is authorized. If it's not, context.Abort(401) should be called.
  98. // The rest of pending handlers would never be called for that request.
  99. func (c *Context) Abort(code int) {
  100. if code >= 0 {
  101. c.Writer.WriteHeader(code)
  102. }
  103. c.index = AbortIndex
  104. }
  105. // Fail is the same as Abort plus an error message.
  106. // Calling `context.Fail(500, err)` is equivalent to:
  107. // ```
  108. // context.Error("Operation aborted", err)
  109. // context.Abort(500)
  110. // ```
  111. func (c *Context) Fail(code int, err error) {
  112. c.Error(err, "Operation aborted")
  113. c.Abort(code)
  114. }
  115. func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {
  116. c.Errors = append(c.Errors, errorMsg{
  117. Err: err.Error(),
  118. Type: typ,
  119. Meta: meta,
  120. })
  121. }
  122. // Attaches an error to the current context. The error is pushed to a list of errors.
  123. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  124. // 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.
  125. func (c *Context) Error(err error, meta interface{}) {
  126. c.ErrorTyped(err, ErrorTypeExternal, meta)
  127. }
  128. func (c *Context) LastError() error {
  129. s := len(c.Errors)
  130. if s > 0 {
  131. return errors.New(c.Errors[s-1].Err)
  132. } else {
  133. return nil
  134. }
  135. }
  136. /************************************/
  137. /******** METADATA MANAGEMENT********/
  138. /************************************/
  139. // Sets a new pair key/value just for the specified context.
  140. // It also lazy initializes the hashmap.
  141. func (c *Context) Set(key string, item interface{}) {
  142. if c.Keys == nil {
  143. c.Keys = make(map[string]interface{})
  144. }
  145. c.Keys[key] = item
  146. }
  147. // Get returns the value for the given key or an error if the key does not exist.
  148. func (c *Context) Get(key string) (interface{}, error) {
  149. if c.Keys != nil {
  150. item, ok := c.Keys[key]
  151. if ok {
  152. return item, nil
  153. }
  154. }
  155. return nil, errors.New("Key does not exist.")
  156. }
  157. // MustGet returns the value for the given key or panics if the value doesn't exist.
  158. func (c *Context) MustGet(key string) interface{} {
  159. value, err := c.Get(key)
  160. if err != nil || value == nil {
  161. log.Panicf("Key %s doesn't exist", key)
  162. }
  163. return value
  164. }
  165. /************************************/
  166. /******** ENCOGING MANAGEMENT********/
  167. /************************************/
  168. // This function checks the Content-Type to select a binding engine automatically,
  169. // Depending the "Content-Type" header different bindings are used:
  170. // "application/json" --> JSON binding
  171. // "application/xml" --> XML binding
  172. // else --> returns an error
  173. // 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.
  174. func (c *Context) Bind(obj interface{}) bool {
  175. var b binding.Binding
  176. ctype := filterFlags(c.Request.Header.Get("Content-Type"))
  177. switch {
  178. case c.Request.Method == "GET" || ctype == MIMEPOSTForm:
  179. b = binding.Form
  180. case ctype == MIMEJSON:
  181. b = binding.JSON
  182. case ctype == MIMEXML || ctype == MIMEXML2:
  183. b = binding.XML
  184. default:
  185. c.Fail(400, errors.New("unknown content-type: "+ctype))
  186. return false
  187. }
  188. return c.BindWith(obj, b)
  189. }
  190. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  191. if err := b.Bind(c.Request, obj); err != nil {
  192. c.Fail(400, err)
  193. return false
  194. }
  195. return true
  196. }
  197. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  198. if err := render.Render(c.Writer, code, obj...); err != nil {
  199. c.ErrorTyped(err, ErrorTypeInternal, obj)
  200. c.Abort(500)
  201. }
  202. }
  203. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  204. // It also sets the Content-Type as "application/json".
  205. func (c *Context) JSON(code int, obj interface{}) {
  206. c.Render(code, render.JSON, obj)
  207. }
  208. // Serializes the given struct as XML into the response body in a fast and efficient way.
  209. // It also sets the Content-Type as "application/xml".
  210. func (c *Context) XML(code int, obj interface{}) {
  211. c.Render(code, render.XML, obj)
  212. }
  213. // Renders the HTTP template specified by its file name.
  214. // It also updates the HTTP code and sets the Content-Type as "text/html".
  215. // See http://golang.org/doc/articles/wiki/
  216. func (c *Context) HTML(code int, name string, obj interface{}) {
  217. c.Render(code, c.Engine.HTMLRender, name, obj)
  218. }
  219. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  220. func (c *Context) String(code int, format string, values ...interface{}) {
  221. c.Render(code, render.Plain, format, values)
  222. }
  223. // Returns a HTTP redirect to the specific location.
  224. func (c *Context) Redirect(code int, location string) {
  225. if code >= 300 && code <= 308 {
  226. c.Render(code, render.Redirect, location)
  227. } else {
  228. panic(fmt.Sprintf("Cannot send a redirect with status code %d", code))
  229. }
  230. }
  231. // Writes some data into the body stream and updates the HTTP code.
  232. func (c *Context) Data(code int, contentType string, data []byte) {
  233. if len(contentType) > 0 {
  234. c.Writer.Header().Set("Content-Type", contentType)
  235. }
  236. if code >= 0 {
  237. c.Writer.WriteHeader(code)
  238. }
  239. c.Writer.Write(data)
  240. }
  241. // Writes the specified file into the body stream
  242. func (c *Context) File(filepath string) {
  243. http.ServeFile(c.Writer, c.Request, filepath)
  244. }