context.go 8.8 KB

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