context.go 9.6 KB

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