context.go 9.2 KB

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