context.go 8.8 KB

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