context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. }
  159. return defaultValue
  160. }
  161. func (c *Context) DefaultFormValue(key, defaultValue string) string {
  162. if va, ok := c.formValue(key); ok {
  163. return va
  164. }
  165. return defaultValue
  166. }
  167. func (c *Context) DefaultParamValue(key, defaultValue string) string {
  168. if va, ok := c.paramValue(key); ok {
  169. return va
  170. }
  171. return defaultValue
  172. }
  173. func (c *Context) paramValue(key string) (string, bool) {
  174. va := c.Params.ByName(key)
  175. return va, len(va) > 0
  176. }
  177. func (c *Context) formValue(key string) (string, bool) {
  178. req := c.Request
  179. req.ParseForm()
  180. if values, ok := req.Form[key]; ok && len(values) > 0 {
  181. return values[0], true
  182. }
  183. return "", false
  184. }
  185. func (c *Context) postFormValue(key string) (string, bool) {
  186. req := c.Request
  187. req.ParseForm()
  188. if values, ok := req.PostForm[key]; ok && len(values) > 0 {
  189. return values[0], true
  190. }
  191. return "", false
  192. }
  193. /************************************/
  194. /******** METADATA MANAGEMENT********/
  195. /************************************/
  196. // Sets a new pair key/value just for the specified context.
  197. // It also lazy initializes the hashmap.
  198. func (c *Context) Set(key string, item interface{}) {
  199. if c.Keys == nil {
  200. c.Keys = make(map[string]interface{})
  201. }
  202. c.Keys[key] = item
  203. }
  204. // Get returns the value for the given key or an error if the key does not exist.
  205. func (c *Context) Get(key string) (value interface{}, ok bool) {
  206. if c.Keys != nil {
  207. value, ok = c.Keys[key]
  208. }
  209. return
  210. }
  211. // MustGet returns the value for the given key or panics if the value doesn't exist.
  212. func (c *Context) MustGet(key string) interface{} {
  213. if value, exists := c.Get(key); exists {
  214. return value
  215. } else {
  216. panic("Key \"" + key + "\" does not exist")
  217. }
  218. }
  219. func (c *Context) Value(key interface{}) interface{} {
  220. if key == 0 {
  221. return c.Request
  222. }
  223. if keyAsString, ok := key.(string); ok {
  224. val, _ := c.Get(keyAsString)
  225. return val
  226. }
  227. return c.Context.Value(key)
  228. }
  229. /************************************/
  230. /********* PARSING REQUEST **********/
  231. /************************************/
  232. func (c *Context) ClientIP() string {
  233. clientIP := c.Request.Header.Get("X-Real-IP")
  234. if len(clientIP) > 0 {
  235. return clientIP
  236. }
  237. clientIP = c.Request.Header.Get("X-Forwarded-For")
  238. clientIP = strings.Split(clientIP, ",")[0]
  239. if len(clientIP) > 0 {
  240. return strings.TrimSpace(clientIP)
  241. }
  242. return c.Request.RemoteAddr
  243. }
  244. func (c *Context) ContentType() string {
  245. return filterFlags(c.Request.Header.Get("Content-Type"))
  246. }
  247. // This function checks the Content-Type to select a binding engine automatically,
  248. // Depending the "Content-Type" header different bindings are used:
  249. // "application/json" --> JSON binding
  250. // "application/xml" --> XML binding
  251. // else --> returns an error
  252. // 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.
  253. func (c *Context) Bind(obj interface{}) bool {
  254. b := binding.Default(c.Request.Method, c.ContentType())
  255. return c.BindWith(obj, b)
  256. }
  257. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  258. if err := b.Bind(c.Request, obj); err != nil {
  259. c.Fail(400, err)
  260. return false
  261. }
  262. return true
  263. }
  264. /************************************/
  265. /******** RESPONSE RENDERING ********/
  266. /************************************/
  267. func (c *Context) renderingError(err error, meta ...interface{}) {
  268. c.ErrorTyped(err, ErrorTypeInternal, meta)
  269. c.AbortWithStatus(500)
  270. }
  271. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  272. if err := render.Render(c.Writer, code, obj...); err != nil {
  273. c.renderingError(err, obj)
  274. }
  275. }
  276. // Renders the HTTP template specified by its file name.
  277. // It also updates the HTTP code and sets the Content-Type as "text/html".
  278. // See http://golang.org/doc/articles/wiki/
  279. func (c *Context) HTML(code int, name string, obj interface{}) {
  280. c.Render(code, c.Engine.HTMLRender, name, obj)
  281. }
  282. func (c *Context) IndentedJSON(code int, obj interface{}) {
  283. if err := render.WriteIndentedJSON(c.Writer, code, obj); err != nil {
  284. c.renderingError(err, obj)
  285. }
  286. }
  287. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  288. // It also sets the Content-Type as "application/json".
  289. func (c *Context) JSON(code int, obj interface{}) {
  290. if err := render.WriteJSON(c.Writer, code, obj); err != nil {
  291. c.renderingError(err, obj)
  292. }
  293. }
  294. // Serializes the given struct as XML into the response body in a fast and efficient way.
  295. // It also sets the Content-Type as "application/xml".
  296. func (c *Context) XML(code int, obj interface{}) {
  297. if err := render.WriteXML(c.Writer, code, obj); err != nil {
  298. c.renderingError(err, obj)
  299. }
  300. }
  301. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  302. func (c *Context) String(code int, format string, values ...interface{}) {
  303. render.WritePlainText(c.Writer, code, format, values)
  304. }
  305. // Writes the given string into the response body and sets the Content-Type to "text/html" without template.
  306. func (c *Context) HTMLString(code int, format string, values ...interface{}) {
  307. render.WriteHTMLString(c.Writer, code, format, values)
  308. }
  309. // Returns a HTTP redirect to the specific location.
  310. func (c *Context) Redirect(code int, location string) {
  311. render.WriteRedirect(c.Writer, code, c.Request, location)
  312. }
  313. // Writes some data into the body stream and updates the HTTP code.
  314. func (c *Context) Data(code int, contentType string, data []byte) {
  315. render.WriteData(c.Writer, code, contentType, data)
  316. }
  317. // Writes the specified file into the body stream
  318. func (c *Context) File(filepath string) {
  319. http.ServeFile(c.Writer, c.Request, filepath)
  320. }
  321. /************************************/
  322. /******** CONTENT NEGOTIATION *******/
  323. /************************************/
  324. type Negotiate struct {
  325. Offered []string
  326. HTMLPath string
  327. HTMLData interface{}
  328. JSONData interface{}
  329. XMLData interface{}
  330. Data interface{}
  331. }
  332. func (c *Context) Negotiate(code int, config Negotiate) {
  333. switch c.NegotiateFormat(config.Offered...) {
  334. case binding.MIMEJSON:
  335. data := chooseData(config.JSONData, config.Data)
  336. c.JSON(code, data)
  337. case binding.MIMEHTML:
  338. if len(config.HTMLPath) == 0 {
  339. panic("negotiate config is wrong. html path is needed")
  340. }
  341. data := chooseData(config.HTMLData, config.Data)
  342. c.HTML(code, config.HTMLPath, data)
  343. case binding.MIMEXML:
  344. data := chooseData(config.XMLData, config.Data)
  345. c.XML(code, data)
  346. default:
  347. c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  348. }
  349. }
  350. func (c *Context) NegotiateFormat(offered ...string) string {
  351. if len(offered) == 0 {
  352. panic("you must provide at least one offer")
  353. }
  354. if c.Accepted == nil {
  355. c.Accepted = parseAccept(c.Request.Header.Get("Accept"))
  356. }
  357. if len(c.Accepted) == 0 {
  358. return offered[0]
  359. }
  360. for _, accepted := range c.Accepted {
  361. for _, offert := range offered {
  362. if accepted == offert {
  363. return offert
  364. }
  365. }
  366. }
  367. return ""
  368. }
  369. func (c *Context) SetAccepted(formats ...string) {
  370. c.Accepted = formats
  371. }