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