context.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. accepted []string
  63. }
  64. /************************************/
  65. /********** ROUTES GROUPING *********/
  66. /************************************/
  67. func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
  68. c := engine.cache.Get().(*Context)
  69. c.writermem.reset(w)
  70. c.Request = req
  71. c.Params = params
  72. c.handlers = handlers
  73. c.Keys = nil
  74. c.index = -1
  75. c.Errors = c.Errors[0:0]
  76. return c
  77. }
  78. /************************************/
  79. /****** FLOW AND ERROR MANAGEMENT****/
  80. /************************************/
  81. func (c *Context) Copy() *Context {
  82. var cp Context = *c
  83. cp.index = AbortIndex
  84. cp.handlers = nil
  85. return &cp
  86. }
  87. // Next should be used only in the middlewares.
  88. // It executes the pending handlers in the chain inside the calling handler.
  89. // See example in github.
  90. func (c *Context) Next() {
  91. c.index++
  92. s := int8(len(c.handlers))
  93. for ; c.index < s; c.index++ {
  94. c.handlers[c.index](c)
  95. }
  96. }
  97. // Forces the system to do not continue calling the pending handlers.
  98. // For example, the first handler checks if the request is authorized. If it's not, context.Abort(401) should be called.
  99. // The rest of pending handlers would never be called for that request.
  100. func (c *Context) Abort(code int) {
  101. if code >= 0 {
  102. c.Writer.WriteHeader(code)
  103. }
  104. c.index = AbortIndex
  105. }
  106. // Fail is the same as Abort plus an error message.
  107. // Calling `context.Fail(500, err)` is equivalent to:
  108. // ```
  109. // context.Error("Operation aborted", err)
  110. // context.Abort(500)
  111. // ```
  112. func (c *Context) Fail(code int, err error) {
  113. c.Error(err, "Operation aborted")
  114. c.Abort(code)
  115. }
  116. func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {
  117. c.Errors = append(c.Errors, errorMsg{
  118. Err: err.Error(),
  119. Type: typ,
  120. Meta: meta,
  121. })
  122. }
  123. // Attaches an error to the current context. The error is pushed to a list of errors.
  124. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  125. // 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.
  126. func (c *Context) Error(err error, meta interface{}) {
  127. c.ErrorTyped(err, ErrorTypeExternal, meta)
  128. }
  129. func (c *Context) LastError() error {
  130. s := len(c.Errors)
  131. if s > 0 {
  132. return errors.New(c.Errors[s-1].Err)
  133. } else {
  134. return nil
  135. }
  136. }
  137. /************************************/
  138. /******** METADATA MANAGEMENT********/
  139. /************************************/
  140. // Sets a new pair key/value just for the specified context.
  141. // It also lazy initializes the hashmap.
  142. func (c *Context) Set(key string, item interface{}) {
  143. if c.Keys == nil {
  144. c.Keys = make(map[string]interface{})
  145. }
  146. c.Keys[key] = item
  147. }
  148. // Get returns the value for the given key or an error if the key does not exist.
  149. func (c *Context) Get(key string) (interface{}, error) {
  150. if c.Keys != nil {
  151. item, ok := c.Keys[key]
  152. if ok {
  153. return item, nil
  154. }
  155. }
  156. return nil, errors.New("Key does not exist.")
  157. }
  158. // MustGet returns the value for the given key or panics if the value doesn't exist.
  159. func (c *Context) MustGet(key string) interface{} {
  160. value, err := c.Get(key)
  161. if err != nil || value == nil {
  162. log.Panicf("Key %s doesn't exist", key)
  163. }
  164. return value
  165. }
  166. /************************************/
  167. /******** ENCOGING MANAGEMENT********/
  168. /************************************/
  169. // This function checks the Content-Type to select a binding engine automatically,
  170. // Depending the "Content-Type" header different bindings are used:
  171. // "application/json" --> JSON binding
  172. // "application/xml" --> XML binding
  173. // else --> returns an error
  174. // 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.
  175. func (c *Context) Bind(obj interface{}) bool {
  176. var b binding.Binding
  177. ctype := filterFlags(c.Request.Header.Get("Content-Type"))
  178. switch {
  179. case c.Request.Method == "GET" || ctype == MIMEPOSTForm:
  180. b = binding.Form
  181. case ctype == MIMEJSON:
  182. b = binding.JSON
  183. case ctype == MIMEXML || ctype == MIMEXML2:
  184. b = binding.XML
  185. default:
  186. c.Fail(400, errors.New("unknown content-type: "+ctype))
  187. return false
  188. }
  189. return c.BindWith(obj, b)
  190. }
  191. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  192. if err := b.Bind(c.Request, obj); err != nil {
  193. c.Fail(400, err)
  194. return false
  195. }
  196. return true
  197. }
  198. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  199. if err := render.Render(c.Writer, code, obj...); err != nil {
  200. c.ErrorTyped(err, ErrorTypeInternal, obj)
  201. c.Abort(500)
  202. }
  203. }
  204. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  205. // It also sets the Content-Type as "application/json".
  206. func (c *Context) JSON(code int, obj interface{}) {
  207. c.Render(code, render.JSON, obj)
  208. }
  209. // Serializes the given struct as XML into the response body in a fast and efficient way.
  210. // It also sets the Content-Type as "application/xml".
  211. func (c *Context) XML(code int, obj interface{}) {
  212. c.Render(code, render.XML, obj)
  213. }
  214. // Renders the HTTP template specified by its file name.
  215. // It also updates the HTTP code and sets the Content-Type as "text/html".
  216. // See http://golang.org/doc/articles/wiki/
  217. func (c *Context) HTML(code int, name string, obj interface{}) {
  218. c.Render(code, c.Engine.HTMLRender, name, obj)
  219. }
  220. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  221. func (c *Context) String(code int, format string, values ...interface{}) {
  222. c.Render(code, render.Plain, format, values)
  223. }
  224. // Returns a HTTP redirect to the specific location.
  225. func (c *Context) Redirect(code int, location string) {
  226. if code >= 300 && code <= 308 {
  227. c.Render(code, render.Redirect, location)
  228. } else {
  229. panic(fmt.Sprintf("Cannot send a redirect with status code %d", code))
  230. }
  231. }
  232. // Writes some data into the body stream and updates the HTTP code.
  233. func (c *Context) Data(code int, contentType string, data []byte) {
  234. if len(contentType) > 0 {
  235. c.Writer.Header().Set("Content-Type", contentType)
  236. }
  237. if code >= 0 {
  238. c.Writer.WriteHeader(code)
  239. }
  240. c.Writer.Write(data)
  241. }
  242. // Writes the specified file into the body stream
  243. func (c *Context) File(filepath string) {
  244. http.ServeFile(c.Writer, c.Request, filepath)
  245. }
  246. /************************************/
  247. /******** CONTENT NEGOTIATION *******/
  248. /************************************/
  249. type Negotiate struct {
  250. Offered []string
  251. Data interface{}
  252. JsonData interface{}
  253. XMLData interface{}
  254. HTMLData interface{}
  255. HTMLPath string
  256. }
  257. func (c *Context) Negotiate2(code int, config Negotiate) {
  258. result := c.NegotiateFormat(config.Offered...)
  259. switch result {
  260. case MIMEJSON:
  261. c.JSON(code, config.Data)
  262. case MIMEHTML:
  263. name := config.HTMLPath
  264. c.HTML(code, name, config.Data)
  265. case MIMEXML:
  266. c.XML(code, config.Data)
  267. default:
  268. c.Fail(400, errors.New("m"))
  269. }
  270. }
  271. func (c *Context) Negotiate(code int, config map[string]interface{}, offerts ...string) {
  272. result := c.NegotiateFormat(offerts...)
  273. switch result {
  274. case MIMEJSON:
  275. data := readData("json.data", config)
  276. c.JSON(code, data)
  277. case MIMEHTML:
  278. data := readData("html.data", config)
  279. name := config["html.path"].(string)
  280. c.HTML(code, name, data)
  281. case MIMEXML:
  282. data := readData("xml.data", config)
  283. c.XML(code, data)
  284. default:
  285. c.Fail(400, errors.New("m"))
  286. }
  287. }
  288. func (c *Context) NegotiateFormat(offered ...string) string {
  289. if c.accepted == nil {
  290. c.accepted = parseAccept(c.Request.Header.Get("Accept"))
  291. }
  292. if len(c.accepted) == 0 {
  293. return offered[0]
  294. } else {
  295. for _, accepted := range c.accepted {
  296. for _, offert := range offered {
  297. if accepted == offert {
  298. return offert
  299. }
  300. }
  301. }
  302. return ""
  303. }
  304. }
  305. func (c *Context) SetAccepted(formats ...string) {
  306. c.accepted = formats
  307. }