context.go 9.3 KB

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