context.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. var b binding.Binding
  156. ctype := filterFlags(c.Request.Header.Get("Content-Type"))
  157. switch {
  158. case c.Request.Method == "GET" || ctype == MIMEPOSTForm:
  159. b = binding.Form
  160. case ctype == MIMEMultipartPOSTForm:
  161. b = binding.MultipartForm
  162. case ctype == MIMEJSON:
  163. b = binding.JSON
  164. case ctype == MIMEXML || ctype == MIMEXML2:
  165. b = binding.XML
  166. default:
  167. c.Fail(400, errors.New("unknown content-type: "+ctype))
  168. return false
  169. }
  170. return c.BindWith(obj, b)
  171. }
  172. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  173. if err := b.Bind(c.Request, obj); err != nil {
  174. c.Fail(400, err)
  175. return false
  176. }
  177. return true
  178. }
  179. /************************************/
  180. /******** RESPONSE RENDERING ********/
  181. /************************************/
  182. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  183. if err := render.Render(c.Writer, code, obj...); err != nil {
  184. c.ErrorTyped(err, ErrorTypeInternal, obj)
  185. c.AbortWithStatus(500)
  186. }
  187. }
  188. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  189. // It also sets the Content-Type as "application/json".
  190. func (c *Context) JSON(code int, obj interface{}) {
  191. c.Render(code, render.JSON, obj)
  192. }
  193. // Serializes the given struct as XML into the response body in a fast and efficient way.
  194. // It also sets the Content-Type as "application/xml".
  195. func (c *Context) XML(code int, obj interface{}) {
  196. c.Render(code, render.XML, obj)
  197. }
  198. // Renders the HTTP template specified by its file name.
  199. // It also updates the HTTP code and sets the Content-Type as "text/html".
  200. // See http://golang.org/doc/articles/wiki/
  201. func (c *Context) HTML(code int, name string, obj interface{}) {
  202. c.Render(code, c.Engine.HTMLRender, name, obj)
  203. }
  204. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  205. func (c *Context) String(code int, format string, values ...interface{}) {
  206. c.Render(code, render.Plain, format, values)
  207. }
  208. // Writes the given string into the response body and sets the Content-Type to "text/html" without template.
  209. func (c *Context) HTMLString(code int, format string, values ...interface{}) {
  210. c.Render(code, render.HTMLPlain, format, values)
  211. }
  212. // Returns a HTTP redirect to the specific location.
  213. func (c *Context) Redirect(code int, location string) {
  214. if code >= 300 && code <= 308 {
  215. c.Render(code, render.Redirect, location)
  216. } else {
  217. log.Panicf("Cannot send a redirect with status code %d", code)
  218. }
  219. }
  220. // Writes some data into the body stream and updates the HTTP code.
  221. func (c *Context) Data(code int, contentType string, data []byte) {
  222. if len(contentType) > 0 {
  223. c.Writer.Header().Set("Content-Type", contentType)
  224. }
  225. c.Writer.WriteHeader(code)
  226. c.Writer.Write(data)
  227. }
  228. // Writes the specified file into the body stream
  229. func (c *Context) File(filepath string) {
  230. http.ServeFile(c.Writer, c.Request, filepath)
  231. }
  232. /************************************/
  233. /******** CONTENT NEGOTIATION *******/
  234. /************************************/
  235. type Negotiate struct {
  236. Offered []string
  237. HTMLPath string
  238. HTMLData interface{}
  239. JSONData interface{}
  240. XMLData interface{}
  241. Data interface{}
  242. }
  243. func (c *Context) Negotiate(code int, config Negotiate) {
  244. switch c.NegotiateFormat(config.Offered...) {
  245. case MIMEJSON:
  246. data := chooseData(config.JSONData, config.Data)
  247. c.JSON(code, data)
  248. case MIMEHTML:
  249. data := chooseData(config.HTMLData, config.Data)
  250. if len(config.HTMLPath) == 0 {
  251. log.Panic("negotiate config is wrong. html path is needed")
  252. }
  253. c.HTML(code, config.HTMLPath, data)
  254. case MIMEXML:
  255. data := chooseData(config.XMLData, config.Data)
  256. c.XML(code, data)
  257. default:
  258. c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  259. }
  260. }
  261. func (c *Context) NegotiateFormat(offered ...string) string {
  262. if len(offered) == 0 {
  263. log.Panic("you must provide at least one offer")
  264. }
  265. if c.accepted == nil {
  266. c.accepted = parseAccept(c.Request.Header.Get("Accept"))
  267. }
  268. if len(c.accepted) == 0 {
  269. return offered[0]
  270. } else {
  271. for _, accepted := range c.accepted {
  272. for _, offert := range offered {
  273. if accepted == offert {
  274. return offert
  275. }
  276. }
  277. }
  278. return ""
  279. }
  280. }
  281. func (c *Context) SetAccepted(formats ...string) {
  282. c.accepted = formats
  283. }