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