context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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) ByName(name string) string {
  36. for _, entry := range ps {
  37. if entry.Key == name {
  38. return entry.Value
  39. }
  40. }
  41. return ""
  42. }
  43. // Context is the most important part of gin. It allows us to pass variables between middleware,
  44. // manage the flow, validate the JSON of a request and render a JSON response for example.
  45. type Context struct {
  46. context.Context
  47. writermem responseWriter
  48. Request *http.Request
  49. Writer ResponseWriter
  50. Params Params
  51. handlers HandlersChain
  52. index int8
  53. Engine *Engine
  54. Keys map[string]interface{}
  55. Errors errorMsgs
  56. Accepted []string
  57. }
  58. /************************************/
  59. /********** CONTEXT CREATION ********/
  60. /************************************/
  61. func (c *Context) reset() {
  62. c.Writer = &c.writermem
  63. c.Params = c.Params[0:0]
  64. c.handlers = nil
  65. c.index = -1
  66. c.Keys = nil
  67. c.Errors = c.Errors[0:0]
  68. c.Accepted = nil
  69. }
  70. func (c *Context) Copy() *Context {
  71. var cp Context = *c
  72. cp.writermem.ResponseWriter = nil
  73. cp.Writer = &cp.writermem
  74. cp.index = AbortIndex
  75. cp.handlers = nil
  76. return &cp
  77. }
  78. /************************************/
  79. /*************** FLOW ***************/
  80. /************************************/
  81. // Next should be used only in the middlewares.
  82. // It executes the pending handlers in the chain inside the calling handler.
  83. // See example in github.
  84. func (c *Context) Next() {
  85. c.index++
  86. s := int8(len(c.handlers))
  87. for ; c.index < s; c.index++ {
  88. c.handlers[c.index](c)
  89. }
  90. }
  91. // Forces the system to not continue calling the pending handlers in the chain.
  92. func (c *Context) Abort() {
  93. c.index = AbortIndex
  94. }
  95. // Same than AbortWithStatus() but also writes the specified response status code.
  96. // For example, the first handler checks if the request is authorized. If it's not, context.AbortWithStatus(401) should be called.
  97. func (c *Context) AbortWithStatus(code int) {
  98. c.Writer.WriteHeader(code)
  99. c.Abort()
  100. }
  101. func (c *Context) IsAborted() bool {
  102. return c.index == AbortIndex
  103. }
  104. /************************************/
  105. /********* ERROR MANAGEMENT *********/
  106. /************************************/
  107. // Fail is the same as Abort plus an error message.
  108. // Calling `context.Fail(500, err)` is equivalent to:
  109. // ```
  110. // context.Error("Operation aborted", err)
  111. // context.AbortWithStatus(500)
  112. // ```
  113. func (c *Context) Fail(code int, err error) {
  114. c.Error(err, "Operation aborted")
  115. c.AbortWithStatus(code)
  116. }
  117. func (c *Context) ErrorTyped(err error, typ int, meta interface{}) {
  118. c.Errors = append(c.Errors, errorMsg{
  119. Err: err.Error(),
  120. Type: typ,
  121. Meta: meta,
  122. })
  123. }
  124. // Attaches an error to the current context. The error is pushed to a list of errors.
  125. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  126. // 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.
  127. func (c *Context) Error(err error, meta interface{}) {
  128. c.ErrorTyped(err, ErrorTypeExternal, meta)
  129. }
  130. func (c *Context) LastError() error {
  131. nuErrors := len(c.Errors)
  132. if nuErrors > 0 {
  133. return errors.New(c.Errors[nuErrors-1].Err)
  134. }
  135. return nil
  136. }
  137. /************************************/
  138. /************ INPUT DATA ************/
  139. /************************************/
  140. /** Shortcut for c.Request.FormValue(key) */
  141. func (c *Context) FormValue(key string) (va string) {
  142. va, _ = c.formValue(key)
  143. return
  144. }
  145. /** Shortcut for c.Request.PostFormValue(key) */
  146. func (c *Context) PostFormValue(key string) (va string) {
  147. va, _ = c.postFormValue(key)
  148. return
  149. }
  150. /** Shortcut for c.Params.ByName(key) */
  151. func (c *Context) ParamValue(key string) (va string) {
  152. va, _ = c.paramValue(key)
  153. return
  154. }
  155. func (c *Context) DefaultPostFormValue(key, defaultValue string) string {
  156. if va, ok := c.postFormValue(key); ok {
  157. return va
  158. } else {
  159. return defaultValue
  160. }
  161. }
  162. func (c *Context) DefaultFormValue(key, defaultValue string) string {
  163. if va, ok := c.formValue(key); ok {
  164. return va
  165. } else {
  166. return defaultValue
  167. }
  168. }
  169. func (c *Context) DefaultParamValue(key, defaultValue string) string {
  170. if va, ok := c.paramValue(key); ok {
  171. return va
  172. } else {
  173. return defaultValue
  174. }
  175. }
  176. func (c *Context) paramValue(key string) (string, bool) {
  177. va := c.Params.ByName(key)
  178. return va, len(va) > 0
  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, item interface{}) {
  202. if c.Keys == nil {
  203. c.Keys = make(map[string]interface{})
  204. }
  205. c.Keys[key] = item
  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{}, ok bool) {
  209. if c.Keys != nil {
  210. value, ok = 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. c.Render(code, render.IndentedJSON, obj)
  287. }
  288. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  289. // It also sets the Content-Type as "application/json".
  290. func (c *Context) JSON(code int, obj interface{}) {
  291. if err := render.WriteJSON(c.Writer, code, obj); err != nil {
  292. c.renderingError(err, obj)
  293. }
  294. }
  295. // Serializes the given struct as XML into the response body in a fast and efficient way.
  296. // It also sets the Content-Type as "application/xml".
  297. func (c *Context) XML(code int, obj interface{}) {
  298. if err := render.WriteXML(c.Writer, code, obj); err != nil {
  299. c.renderingError(err, obj)
  300. }
  301. }
  302. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  303. func (c *Context) String(code int, format string, values ...interface{}) {
  304. render.WritePlainText(c.Writer, code, format, values)
  305. }
  306. // Writes the given string into the response body and sets the Content-Type to "text/html" without template.
  307. func (c *Context) HTMLString(code int, format string, values ...interface{}) {
  308. render.WriteHTMLString(c.Writer, code, format, values)
  309. }
  310. // Returns a HTTP redirect to the specific location.
  311. func (c *Context) Redirect(code int, location string) {
  312. render.WriteRedirect(c.Writer, code, c.Request, location)
  313. }
  314. // Writes some data into the body stream and updates the HTTP code.
  315. func (c *Context) Data(code int, contentType string, data []byte) {
  316. render.WriteData(c.Writer, code, contentType, data)
  317. }
  318. // Writes the specified file into the body stream
  319. func (c *Context) File(filepath string) {
  320. http.ServeFile(c.Writer, c.Request, filepath)
  321. }
  322. /************************************/
  323. /******** CONTENT NEGOTIATION *******/
  324. /************************************/
  325. type Negotiate struct {
  326. Offered []string
  327. HTMLPath string
  328. HTMLData interface{}
  329. JSONData interface{}
  330. XMLData interface{}
  331. Data interface{}
  332. }
  333. func (c *Context) Negotiate(code int, config Negotiate) {
  334. switch c.NegotiateFormat(config.Offered...) {
  335. case binding.MIMEJSON:
  336. data := chooseData(config.JSONData, config.Data)
  337. c.JSON(code, data)
  338. case binding.MIMEHTML:
  339. if len(config.HTMLPath) == 0 {
  340. panic("negotiate config is wrong. html path is needed")
  341. }
  342. data := chooseData(config.HTMLData, config.Data)
  343. c.HTML(code, config.HTMLPath, data)
  344. case binding.MIMEXML:
  345. data := chooseData(config.XMLData, config.Data)
  346. c.XML(code, data)
  347. default:
  348. c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  349. }
  350. }
  351. func (c *Context) NegotiateFormat(offered ...string) string {
  352. if len(offered) == 0 {
  353. panic("you must provide at least one offer")
  354. }
  355. if c.Accepted == nil {
  356. c.Accepted = parseAccept(c.Request.Header.Get("Accept"))
  357. }
  358. if len(c.Accepted) == 0 {
  359. return offered[0]
  360. }
  361. for _, accepted := range c.Accepted {
  362. for _, offert := range offered {
  363. if accepted == offert {
  364. return offert
  365. }
  366. }
  367. }
  368. return ""
  369. }
  370. func (c *Context) SetAccepted(formats ...string) {
  371. c.Accepted = formats
  372. }