context.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. func (c *Context) ClientIP() string {
  175. clientIP := c.Request.Header.Get("X-Real-IP")
  176. if len(clientIP) == 0 {
  177. clientIP = c.Request.Header.Get("X-Forwarded-For")
  178. }
  179. if len(clientIP) == 0 {
  180. clientIP = c.Request.RemoteAddr
  181. }
  182. return clientIP
  183. }
  184. /************************************/
  185. /********* PARSING REQUEST **********/
  186. /************************************/
  187. // This function checks the Content-Type to select a binding engine automatically,
  188. // Depending the "Content-Type" header different bindings are used:
  189. // "application/json" --> JSON binding
  190. // "application/xml" --> XML binding
  191. // else --> returns an error
  192. // 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.
  193. func (c *Context) Bind(obj interface{}) bool {
  194. var b binding.Binding
  195. ctype := filterFlags(c.Request.Header.Get("Content-Type"))
  196. switch {
  197. case c.Request.Method == "GET" || ctype == MIMEPOSTForm:
  198. b = binding.Form
  199. case ctype == MIMEJSON:
  200. b = binding.JSON
  201. case ctype == MIMEXML || ctype == MIMEXML2:
  202. b = binding.XML
  203. default:
  204. c.Fail(400, errors.New("unknown content-type: "+ctype))
  205. return false
  206. }
  207. return c.BindWith(obj, b)
  208. }
  209. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  210. if err := b.Bind(c.Request, obj); err != nil {
  211. c.Fail(400, err)
  212. return false
  213. }
  214. return true
  215. }
  216. /************************************/
  217. /******** RESPONSE RENDERING ********/
  218. /************************************/
  219. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  220. if err := render.Render(c.Writer, code, obj...); err != nil {
  221. c.ErrorTyped(err, ErrorTypeInternal, obj)
  222. c.AbortWithStatus(500)
  223. }
  224. }
  225. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  226. // It also sets the Content-Type as "application/json".
  227. func (c *Context) JSON(code int, obj interface{}) {
  228. c.Render(code, render.JSON, obj)
  229. }
  230. // Serializes the given struct as XML into the response body in a fast and efficient way.
  231. // It also sets the Content-Type as "application/xml".
  232. func (c *Context) XML(code int, obj interface{}) {
  233. c.Render(code, render.XML, obj)
  234. }
  235. // Renders the HTTP template specified by its file name.
  236. // It also updates the HTTP code and sets the Content-Type as "text/html".
  237. // See http://golang.org/doc/articles/wiki/
  238. func (c *Context) HTML(code int, name string, obj interface{}) {
  239. c.Render(code, c.Engine.HTMLRender, name, obj)
  240. }
  241. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  242. func (c *Context) String(code int, format string, values ...interface{}) {
  243. c.Render(code, render.Plain, format, values)
  244. }
  245. // Returns a HTTP redirect to the specific location.
  246. func (c *Context) Redirect(code int, location string) {
  247. if code >= 300 && code <= 308 {
  248. c.Render(code, render.Redirect, location)
  249. } else {
  250. panic(fmt.Sprintf("Cannot send a redirect with status code %d", code))
  251. }
  252. }
  253. // Writes some data into the body stream and updates the HTTP code.
  254. func (c *Context) Data(code int, contentType string, data []byte) {
  255. if len(contentType) > 0 {
  256. c.Writer.Header().Set("Content-Type", contentType)
  257. }
  258. c.Writer.WriteHeader(code)
  259. c.Writer.Write(data)
  260. }
  261. // Writes the specified file into the body stream
  262. func (c *Context) File(filepath string) {
  263. http.ServeFile(c.Writer, c.Request, filepath)
  264. }
  265. /************************************/
  266. /******** CONTENT NEGOTIATION *******/
  267. /************************************/
  268. type Negotiate struct {
  269. Offered []string
  270. HTMLPath string
  271. HTMLData interface{}
  272. JSONData interface{}
  273. XMLData interface{}
  274. Data interface{}
  275. }
  276. func (c *Context) Negotiate(code int, config Negotiate) {
  277. switch c.NegotiateFormat(config.Offered...) {
  278. case MIMEJSON:
  279. data := chooseData(config.JSONData, config.Data)
  280. c.JSON(code, data)
  281. case MIMEHTML:
  282. data := chooseData(config.HTMLData, config.Data)
  283. if len(config.HTMLPath) == 0 {
  284. panic("negotiate config is wrong. html path is needed")
  285. }
  286. c.HTML(code, config.HTMLPath, data)
  287. case MIMEXML:
  288. data := chooseData(config.XMLData, config.Data)
  289. c.XML(code, data)
  290. default:
  291. c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  292. }
  293. }
  294. func (c *Context) NegotiateFormat(offered ...string) string {
  295. if len(offered) == 0 {
  296. panic("you must provide at least one offer")
  297. }
  298. if c.accepted == nil {
  299. c.accepted = parseAccept(c.Request.Header.Get("Accept"))
  300. }
  301. if len(c.accepted) == 0 {
  302. return offered[0]
  303. } else {
  304. for _, accepted := range c.accepted {
  305. for _, offert := range offered {
  306. if accepted == offert {
  307. return offert
  308. }
  309. }
  310. }
  311. return ""
  312. }
  313. }
  314. func (c *Context) SetAccepted(formats ...string) {
  315. c.accepted = formats
  316. }