context.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. "errors"
  7. "log"
  8. "math"
  9. "net/http"
  10. "strings"
  11. "github.com/gin-gonic/gin/binding"
  12. "github.com/gin-gonic/gin/render"
  13. )
  14. const AbortIndex = math.MaxInt8 / 2
  15. // Context is the most important part of gin. It allows us to pass variables between middleware,
  16. // manage the flow, validate the JSON of a request and render a JSON response for example.
  17. type Context struct {
  18. writermem responseWriter
  19. Request *http.Request
  20. Writer ResponseWriter
  21. Params Params
  22. Input inputHolder
  23. handlers []HandlerFunc
  24. index int8
  25. Engine *Engine
  26. Keys map[string]interface{}
  27. Errors errorMsgs
  28. accepted []string
  29. }
  30. /************************************/
  31. /********** CONTEXT CREATION ********/
  32. /************************************/
  33. func (c *Context) reset() {
  34. c.Writer = &c.writermem
  35. c.Params = c.Params[0:0]
  36. c.handlers = nil
  37. c.index = -1
  38. c.Keys = nil
  39. c.Errors = c.Errors[0:0]
  40. c.accepted = nil
  41. }
  42. func (c *Context) Copy() *Context {
  43. var cp Context = *c
  44. cp.index = AbortIndex
  45. cp.handlers = nil
  46. return &cp
  47. }
  48. /************************************/
  49. /*************** FLOW ***************/
  50. /************************************/
  51. // Next should be used only in the middlewares.
  52. // It executes the pending handlers in the chain inside the calling handler.
  53. // See example in github.
  54. func (c *Context) Next() {
  55. c.index++
  56. s := int8(len(c.handlers))
  57. for ; c.index < s; c.index++ {
  58. c.handlers[c.index](c)
  59. }
  60. }
  61. // Forces the system to not continue calling the pending handlers in the chain.
  62. func (c *Context) Abort() {
  63. c.index = AbortIndex
  64. }
  65. // Same than AbortWithStatus() but also writes the specified response status code.
  66. // For example, the first handler checks if the request is authorized. If it's not, context.AbortWithStatus(401) should be called.
  67. func (c *Context) AbortWithStatus(code int) {
  68. c.Writer.WriteHeader(code)
  69. c.Abort()
  70. }
  71. /************************************/
  72. /********* ERROR MANAGEMENT *********/
  73. /************************************/
  74. // Fail is the same as Abort plus an error message.
  75. // Calling `context.Fail(500, err)` is equivalent to:
  76. // ```
  77. // context.Error("Operation aborted", err)
  78. // context.AbortWithStatus(500)
  79. // ```
  80. func (c *Context) Fail(code int, err error) {
  81. c.Error(err, "Operation aborted")
  82. c.AbortWithStatus(code)
  83. }
  84. func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {
  85. c.Errors = append(c.Errors, errorMsg{
  86. Err: err.Error(),
  87. Type: typ,
  88. Meta: meta,
  89. })
  90. }
  91. // Attaches an error to the current context. The error is pushed to a list of errors.
  92. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  93. // 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.
  94. func (c *Context) Error(err error, meta interface{}) {
  95. c.ErrorTyped(err, ErrorTypeExternal, meta)
  96. }
  97. func (c *Context) LastError() error {
  98. nuErrors := len(c.Errors)
  99. if nuErrors > 0 {
  100. return errors.New(c.Errors[nuErrors-1].Err)
  101. }
  102. return nil
  103. }
  104. /************************************/
  105. /******** METADATA MANAGEMENT********/
  106. /************************************/
  107. // Sets a new pair key/value just for the specified context.
  108. // It also lazy initializes the hashmap.
  109. func (c *Context) Set(key string, item interface{}) {
  110. if c.Keys == nil {
  111. c.Keys = make(map[string]interface{})
  112. }
  113. c.Keys[key] = item
  114. }
  115. // Get returns the value for the given key or an error if the key does not exist.
  116. func (c *Context) Get(key string) (value interface{}, ok bool) {
  117. if c.Keys != nil {
  118. value, ok = c.Keys[key]
  119. }
  120. return
  121. }
  122. // MustGet returns the value for the given key or panics if the value doesn't exist.
  123. func (c *Context) MustGet(key string) interface{} {
  124. if value, exists := c.Get(key); exists {
  125. return value
  126. } else {
  127. log.Panicf("Key %s does not exist", key)
  128. }
  129. return nil
  130. }
  131. /************************************/
  132. /********* PARSING REQUEST **********/
  133. /************************************/
  134. func (c *Context) ClientIP() string {
  135. clientIP := c.Request.Header.Get("X-Real-IP")
  136. if len(clientIP) > 0 {
  137. return clientIP
  138. }
  139. clientIP = c.Request.Header.Get("X-Forwarded-For")
  140. clientIP = strings.Split(clientIP, ",")[0]
  141. if len(clientIP) > 0 {
  142. return clientIP
  143. }
  144. return c.Request.RemoteAddr
  145. }
  146. func (c *Context) ContentType() string {
  147. return filterFlags(c.Request.Header.Get("Content-Type"))
  148. }
  149. // This function checks the Content-Type to select a binding engine automatically,
  150. // Depending the "Content-Type" header different bindings are used:
  151. // "application/json" --> JSON binding
  152. // "application/xml" --> XML binding
  153. // else --> returns an error
  154. // 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.
  155. func (c *Context) Bind(obj interface{}) bool {
  156. b := binding.Default(c.Request.Method, c.ContentType())
  157. return c.BindWith(obj, b)
  158. }
  159. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  160. if err := b.Bind(c.Request, obj); err != nil {
  161. c.Fail(400, err)
  162. return false
  163. }
  164. return true
  165. }
  166. /************************************/
  167. /******** RESPONSE RENDERING ********/
  168. /************************************/
  169. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  170. if err := render.Render(c.Writer, code, obj...); err != nil {
  171. c.ErrorTyped(err, ErrorTypeInternal, obj)
  172. c.AbortWithStatus(500)
  173. }
  174. }
  175. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  176. // It also sets the Content-Type as "application/json".
  177. func (c *Context) JSON(code int, obj interface{}) {
  178. c.Render(code, render.JSON, obj)
  179. }
  180. // Serializes the given struct as XML into the response body in a fast and efficient way.
  181. // It also sets the Content-Type as "application/xml".
  182. func (c *Context) XML(code int, obj interface{}) {
  183. c.Render(code, render.XML, obj)
  184. }
  185. // Renders the HTTP template specified by its file name.
  186. // It also updates the HTTP code and sets the Content-Type as "text/html".
  187. // See http://golang.org/doc/articles/wiki/
  188. func (c *Context) HTML(code int, name string, obj interface{}) {
  189. c.Render(code, c.Engine.HTMLRender, name, obj)
  190. }
  191. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  192. func (c *Context) String(code int, format string, values ...interface{}) {
  193. c.Render(code, render.Plain, format, values)
  194. }
  195. // Writes the given string into the response body and sets the Content-Type to "text/html" without template.
  196. func (c *Context) HTMLString(code int, format string, values ...interface{}) {
  197. c.Render(code, render.HTMLPlain, format, values)
  198. }
  199. // Returns a HTTP redirect to the specific location.
  200. func (c *Context) Redirect(code int, location string) {
  201. if code >= 300 && code <= 308 {
  202. c.Render(code, render.Redirect, location)
  203. } else {
  204. log.Panicf("Cannot send a redirect with status code %d", code)
  205. }
  206. }
  207. // Writes some data into the body stream and updates the HTTP code.
  208. func (c *Context) Data(code int, contentType string, data []byte) {
  209. if len(contentType) > 0 {
  210. c.Writer.Header().Set("Content-Type", contentType)
  211. }
  212. c.Writer.WriteHeader(code)
  213. c.Writer.Write(data)
  214. }
  215. // Writes the specified file into the body stream
  216. func (c *Context) File(filepath string) {
  217. http.ServeFile(c.Writer, c.Request, filepath)
  218. }
  219. /************************************/
  220. /******** CONTENT NEGOTIATION *******/
  221. /************************************/
  222. type Negotiate struct {
  223. Offered []string
  224. HTMLPath string
  225. HTMLData interface{}
  226. JSONData interface{}
  227. XMLData interface{}
  228. Data interface{}
  229. }
  230. func (c *Context) Negotiate(code int, config Negotiate) {
  231. switch c.NegotiateFormat(config.Offered...) {
  232. case binding.MIMEJSON:
  233. data := chooseData(config.JSONData, config.Data)
  234. c.JSON(code, data)
  235. case binding.MIMEHTML:
  236. if len(config.HTMLPath) == 0 {
  237. log.Panic("negotiate config is wrong. html path is needed")
  238. }
  239. data := chooseData(config.HTMLData, config.Data)
  240. c.HTML(code, config.HTMLPath, data)
  241. case binding.MIMEXML:
  242. data := chooseData(config.XMLData, config.Data)
  243. c.XML(code, data)
  244. default:
  245. c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  246. }
  247. }
  248. func (c *Context) NegotiateFormat(offered ...string) string {
  249. if len(offered) == 0 {
  250. log.Panic("you must provide at least one offer")
  251. }
  252. if c.accepted == nil {
  253. c.accepted = parseAccept(c.Request.Header.Get("Accept"))
  254. }
  255. if len(c.accepted) == 0 {
  256. return offered[0]
  257. } else {
  258. for _, accepted := range c.accepted {
  259. for _, offert := range offered {
  260. if accepted == offert {
  261. return offert
  262. }
  263. }
  264. }
  265. return ""
  266. }
  267. }
  268. func (c *Context) SetAccepted(formats ...string) {
  269. c.accepted = formats
  270. }