context.go 12 KB

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