context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. "math"
  8. "net/http"
  9. "strings"
  10. "github.com/gin-gonic/gin/binding"
  11. "github.com/gin-gonic/gin/render"
  12. "golang.org/x/net/context"
  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. // Param is a single URL parameter, consisting of a key and a value.
  25. type Param struct {
  26. Key string
  27. Value string
  28. }
  29. // Params is a Param-slice, as returned by the router.
  30. // The slice is ordered, the first URL parameter is also the first slice value.
  31. // It is therefore safe to read values by the index.
  32. type Params []Param
  33. // ByName returns the value of the first Param which key matches the given name.
  34. // If no matching Param is found, an empty string is returned.
  35. func (ps Params) Get(name string) (string, bool) {
  36. for _, entry := range ps {
  37. if entry.Key == name {
  38. return entry.Value, true
  39. }
  40. }
  41. return "", false
  42. }
  43. func (ps Params) ByName(name string) (va string) {
  44. va, _ = ps.Get(name)
  45. return
  46. }
  47. // Context is the most important part of gin. It allows us to pass variables between middleware,
  48. // manage the flow, validate the JSON of a request and render a JSON response for example.
  49. type Context struct {
  50. context.Context
  51. writermem responseWriter
  52. Request *http.Request
  53. Writer ResponseWriter
  54. Params Params
  55. handlers HandlersChain
  56. index int8
  57. Engine *Engine
  58. Keys map[string]interface{}
  59. Errors errorMsgs
  60. Accepted []string
  61. }
  62. /************************************/
  63. /********** CONTEXT CREATION ********/
  64. /************************************/
  65. func (c *Context) reset() {
  66. c.Writer = &c.writermem
  67. c.Params = c.Params[0:0]
  68. c.handlers = nil
  69. c.index = -1
  70. c.Keys = nil
  71. c.Errors = c.Errors[0:0]
  72. c.Accepted = nil
  73. }
  74. func (c *Context) Copy() *Context {
  75. var cp Context = *c
  76. cp.writermem.ResponseWriter = nil
  77. cp.Writer = &cp.writermem
  78. cp.index = AbortIndex
  79. cp.handlers = nil
  80. return &cp
  81. }
  82. /************************************/
  83. /*************** FLOW ***************/
  84. /************************************/
  85. // Next should be used only in the middlewares.
  86. // It executes the pending handlers in the chain inside the calling handler.
  87. // See example in github.
  88. func (c *Context) Next() {
  89. c.index++
  90. s := int8(len(c.handlers))
  91. for ; c.index < s; c.index++ {
  92. c.handlers[c.index](c)
  93. }
  94. }
  95. // Forces the system to not continue calling the pending handlers in the chain.
  96. func (c *Context) Abort() {
  97. c.index = AbortIndex
  98. }
  99. // Same than AbortWithStatus() but also writes the specified response status code.
  100. // For example, the first handler checks if the request is authorized. If it's not, context.AbortWithStatus(401) should be called.
  101. func (c *Context) AbortWithStatus(code int) {
  102. c.Writer.WriteHeader(code)
  103. c.Abort()
  104. }
  105. func (c *Context) IsAborted() bool {
  106. return c.index == AbortIndex
  107. }
  108. /************************************/
  109. /********* ERROR MANAGEMENT *********/
  110. /************************************/
  111. // Fail is the same as Abort plus an error message.
  112. // Calling `context.Fail(500, err)` is equivalent to:
  113. // ```
  114. // context.Error("Operation aborted", err)
  115. // context.AbortWithStatus(500)
  116. // ```
  117. func (c *Context) Fail(code int, err error) {
  118. c.Error(err, "Operation aborted")
  119. c.AbortWithStatus(code)
  120. }
  121. func (c *Context) ErrorTyped(err error, typ int, meta interface{}) {
  122. c.Errors = append(c.Errors, errorMsg{
  123. Error: err,
  124. Flags: typ,
  125. Meta: meta,
  126. })
  127. }
  128. // Attaches an error to the current context. The error is pushed to a list of errors.
  129. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  130. // 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.
  131. func (c *Context) Error(err error, meta interface{}) {
  132. c.ErrorTyped(err, ErrorTypeExternal, meta)
  133. }
  134. func (c *Context) LastError() error {
  135. nuErrors := len(c.Errors)
  136. if nuErrors > 0 {
  137. return c.Errors[nuErrors-1].Error
  138. }
  139. return nil
  140. }
  141. /************************************/
  142. /************ INPUT DATA ************/
  143. /************************************/
  144. /** Shortcut for c.Request.FormValue(key) */
  145. func (c *Context) FormValue(key string) (va string) {
  146. va, _ = c.formValue(key)
  147. return
  148. }
  149. /** Shortcut for c.Request.PostFormValue(key) */
  150. func (c *Context) PostFormValue(key string) (va string) {
  151. va, _ = c.postFormValue(key)
  152. return
  153. }
  154. /** Shortcut for c.Params.ByName(key) */
  155. func (c *Context) ParamValue(key string) (va string) {
  156. va, _ = c.paramValue(key)
  157. return
  158. }
  159. func (c *Context) DefaultPostFormValue(key, defaultValue string) string {
  160. if va, ok := c.postFormValue(key); ok {
  161. return va
  162. }
  163. return defaultValue
  164. }
  165. func (c *Context) DefaultFormValue(key, defaultValue string) string {
  166. if va, ok := c.formValue(key); ok {
  167. return va
  168. }
  169. return defaultValue
  170. }
  171. func (c *Context) DefaultParamValue(key, defaultValue string) string {
  172. if va, ok := c.paramValue(key); ok {
  173. return va
  174. }
  175. return defaultValue
  176. }
  177. func (c *Context) paramValue(key string) (string, bool) {
  178. return c.Params.Get(key)
  179. }
  180. func (c *Context) formValue(key string) (string, bool) {
  181. req := c.Request
  182. req.ParseForm()
  183. if values, ok := req.Form[key]; ok && len(values) > 0 {
  184. return values[0], true
  185. }
  186. return "", false
  187. }
  188. func (c *Context) postFormValue(key string) (string, bool) {
  189. req := c.Request
  190. req.ParseForm()
  191. if values, ok := req.PostForm[key]; ok && len(values) > 0 {
  192. return values[0], true
  193. }
  194. return "", false
  195. }
  196. /************************************/
  197. /******** METADATA MANAGEMENT********/
  198. /************************************/
  199. // Sets a new pair key/value just for the specified context.
  200. // It also lazy initializes the hashmap.
  201. func (c *Context) Set(key string, value interface{}) {
  202. if c.Keys == nil {
  203. c.Keys = make(map[string]interface{})
  204. }
  205. c.Keys[key] = value
  206. }
  207. // Get returns the value for the given key or an error if the key does not exist.
  208. func (c *Context) Get(key string) (value interface{}, exists bool) {
  209. if c.Keys != nil {
  210. value, exists = c.Keys[key]
  211. }
  212. return
  213. }
  214. // MustGet returns the value for the given key or panics if the value doesn't exist.
  215. func (c *Context) MustGet(key string) interface{} {
  216. if value, exists := c.Get(key); exists {
  217. return value
  218. } else {
  219. panic("Key \"" + key + "\" does not exist")
  220. }
  221. }
  222. func (c *Context) Value(key interface{}) interface{} {
  223. if key == 0 {
  224. return c.Request
  225. }
  226. if keyAsString, ok := key.(string); ok {
  227. val, _ := c.Get(keyAsString)
  228. return val
  229. }
  230. return c.Context.Value(key)
  231. }
  232. /************************************/
  233. /********* PARSING REQUEST **********/
  234. /************************************/
  235. func (c *Context) ClientIP() string {
  236. clientIP := c.Request.Header.Get("X-Real-IP")
  237. if len(clientIP) > 0 {
  238. return clientIP
  239. }
  240. clientIP = c.Request.Header.Get("X-Forwarded-For")
  241. clientIP = strings.Split(clientIP, ",")[0]
  242. if len(clientIP) > 0 {
  243. return strings.TrimSpace(clientIP)
  244. }
  245. return c.Request.RemoteAddr
  246. }
  247. func (c *Context) ContentType() string {
  248. return filterFlags(c.Request.Header.Get("Content-Type"))
  249. }
  250. // This function checks the Content-Type to select a binding engine automatically,
  251. // Depending the "Content-Type" header different bindings are used:
  252. // "application/json" --> JSON binding
  253. // "application/xml" --> XML binding
  254. // else --> returns an error
  255. // 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.
  256. func (c *Context) Bind(obj interface{}) bool {
  257. b := binding.Default(c.Request.Method, c.ContentType())
  258. return c.BindWith(obj, b)
  259. }
  260. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  261. if err := b.Bind(c.Request, obj); err != nil {
  262. c.Fail(400, err)
  263. return false
  264. }
  265. return true
  266. }
  267. /************************************/
  268. /******** RESPONSE RENDERING ********/
  269. /************************************/
  270. func (c *Context) renderingError(err error, meta ...interface{}) {
  271. c.ErrorTyped(err, ErrorTypeInternal, meta)
  272. c.AbortWithStatus(500)
  273. }
  274. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  275. if err := render.Render(c.Writer, code, obj...); err != nil {
  276. c.renderingError(err, obj)
  277. }
  278. }
  279. // Renders the HTTP template specified by its file name.
  280. // It also updates the HTTP code and sets the Content-Type as "text/html".
  281. // See http://golang.org/doc/articles/wiki/
  282. func (c *Context) HTML(code int, name string, obj interface{}) {
  283. c.Render(code, c.Engine.HTMLRender, name, obj)
  284. }
  285. func (c *Context) IndentedJSON(code int, obj interface{}) {
  286. if err := render.WriteIndentedJSON(c.Writer, code, obj); err != nil {
  287. c.renderingError(err, obj)
  288. }
  289. }
  290. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  291. // It also sets the Content-Type as "application/json".
  292. func (c *Context) JSON(code int, obj interface{}) {
  293. if err := render.WriteJSON(c.Writer, code, obj); err != nil {
  294. c.renderingError(err, obj)
  295. }
  296. }
  297. // Serializes the given struct as XML into the response body in a fast and efficient way.
  298. // It also sets the Content-Type as "application/xml".
  299. func (c *Context) XML(code int, obj interface{}) {
  300. if err := render.WriteXML(c.Writer, code, obj); err != nil {
  301. c.renderingError(err, obj)
  302. }
  303. }
  304. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  305. func (c *Context) String(code int, format string, values ...interface{}) {
  306. render.WritePlainText(c.Writer, code, format, values)
  307. }
  308. // Writes the given string into the response body and sets the Content-Type to "text/html" without template.
  309. func (c *Context) HTMLString(code int, format string, values ...interface{}) {
  310. render.WriteHTMLString(c.Writer, code, format, values)
  311. }
  312. // Returns a HTTP redirect to the specific location.
  313. func (c *Context) Redirect(code int, location string) {
  314. render.WriteRedirect(c.Writer, code, c.Request, location)
  315. }
  316. // Writes some data into the body stream and updates the HTTP code.
  317. func (c *Context) Data(code int, contentType string, data []byte) {
  318. render.WriteData(c.Writer, code, contentType, data)
  319. }
  320. // Writes the specified file into the body stream
  321. func (c *Context) File(filepath string) {
  322. http.ServeFile(c.Writer, c.Request, filepath)
  323. }
  324. func (c *Context) Stream(step func(w http.ResponseWriter)) {
  325. w := c.Writer
  326. clientGone := w.CloseNotify()
  327. for {
  328. select {
  329. case <-clientGone:
  330. return
  331. default:
  332. step(w)
  333. w.Flush()
  334. }
  335. }
  336. }
  337. /************************************/
  338. /******** CONTENT NEGOTIATION *******/
  339. /************************************/
  340. type Negotiate struct {
  341. Offered []string
  342. HTMLPath string
  343. HTMLData interface{}
  344. JSONData interface{}
  345. XMLData interface{}
  346. Data interface{}
  347. }
  348. func (c *Context) Negotiate(code int, config Negotiate) {
  349. switch c.NegotiateFormat(config.Offered...) {
  350. case binding.MIMEJSON:
  351. data := chooseData(config.JSONData, config.Data)
  352. c.JSON(code, data)
  353. case binding.MIMEHTML:
  354. if len(config.HTMLPath) == 0 {
  355. panic("negotiate config is wrong. html path is needed")
  356. }
  357. data := chooseData(config.HTMLData, config.Data)
  358. c.HTML(code, config.HTMLPath, data)
  359. case binding.MIMEXML:
  360. data := chooseData(config.XMLData, config.Data)
  361. c.XML(code, data)
  362. default:
  363. c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  364. }
  365. }
  366. func (c *Context) NegotiateFormat(offered ...string) string {
  367. if len(offered) == 0 {
  368. panic("you must provide at least one offer")
  369. }
  370. if c.Accepted == nil {
  371. c.Accepted = parseAccept(c.Request.Header.Get("Accept"))
  372. }
  373. if len(c.Accepted) == 0 {
  374. return offered[0]
  375. }
  376. for _, accepted := range c.Accepted {
  377. for _, offert := range offered {
  378. if accepted == offert {
  379. return offert
  380. }
  381. }
  382. }
  383. return ""
  384. }
  385. func (c *Context) SetAccepted(formats ...string) {
  386. c.Accepted = formats
  387. }