context.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. "io/ioutil"
  9. "math"
  10. "mime/multipart"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "strings"
  15. "time"
  16. "github.com/gin-contrib/sse"
  17. "github.com/gin-gonic/gin/binding"
  18. "github.com/gin-gonic/gin/render"
  19. )
  20. // Content-Type MIME of the most common data formats
  21. const (
  22. MIMEJSON = binding.MIMEJSON
  23. MIMEHTML = binding.MIMEHTML
  24. MIMEXML = binding.MIMEXML
  25. MIMEXML2 = binding.MIMEXML2
  26. MIMEPlain = binding.MIMEPlain
  27. MIMEPOSTForm = binding.MIMEPOSTForm
  28. MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
  29. )
  30. const (
  31. defaultMemory = 32 << 20 // 32 MB
  32. abortIndex int8 = math.MaxInt8 / 2
  33. )
  34. // Context is the most important part of gin. It allows us to pass variables between middleware,
  35. // manage the flow, validate the JSON of a request and render a JSON response for example.
  36. type Context struct {
  37. writermem responseWriter
  38. Request *http.Request
  39. Writer ResponseWriter
  40. Params Params
  41. handlers HandlersChain
  42. index int8
  43. engine *Engine
  44. Keys map[string]interface{}
  45. Errors errorMsgs
  46. Accepted []string
  47. }
  48. /************************************/
  49. /********** CONTEXT CREATION ********/
  50. /************************************/
  51. func (c *Context) reset() {
  52. c.Writer = &c.writermem
  53. c.Params = c.Params[0:0]
  54. c.handlers = nil
  55. c.index = -1
  56. c.Keys = nil
  57. c.Errors = c.Errors[0:0]
  58. c.Accepted = nil
  59. }
  60. // Copy returns a copy of the current context that can be safely used outside the request's scope.
  61. // This has to be used when the context has to be passed to a goroutine.
  62. func (c *Context) Copy() *Context {
  63. var cp = *c
  64. cp.writermem.ResponseWriter = nil
  65. cp.Writer = &cp.writermem
  66. cp.index = abortIndex
  67. cp.handlers = nil
  68. return &cp
  69. }
  70. // HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", this
  71. // function will return "main.handleGetUsers"
  72. func (c *Context) HandlerName() string {
  73. return nameOfFunction(c.handlers.Last())
  74. }
  75. // Handler returns the main handler.
  76. func (c *Context) Handler() HandlerFunc {
  77. return c.handlers.Last()
  78. }
  79. /************************************/
  80. /*********** FLOW CONTROL ***********/
  81. /************************************/
  82. // Next should be used only inside middleware.
  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. // IsAborted returns true if the current context was aborted.
  93. func (c *Context) IsAborted() bool {
  94. return c.index >= abortIndex
  95. }
  96. // Abort prevents pending handlers from being called. Note that this will not stop the current handler.
  97. // Let's say you have an authorization middleware that validates that the current request is authorized. If the
  98. // authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
  99. // for this request are not called.
  100. func (c *Context) Abort() {
  101. c.index = abortIndex
  102. }
  103. // AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
  104. // For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
  105. func (c *Context) AbortWithStatus(code int) {
  106. c.Status(code)
  107. c.Writer.WriteHeaderNow()
  108. c.Abort()
  109. }
  110. // AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body
  111. // It also sets the Content-Type as "application/json".
  112. func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) {
  113. c.Abort()
  114. c.JSON(code, jsonObj)
  115. }
  116. // AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and
  117. // pushes the specified error to `c.Errors`.
  118. // See Context.Error() for more details.
  119. func (c *Context) AbortWithError(code int, err error) *Error {
  120. c.AbortWithStatus(code)
  121. return c.Error(err)
  122. }
  123. /************************************/
  124. /********* ERROR MANAGEMENT *********/
  125. /************************************/
  126. // Attaches an error to the current context. The error is pushed to a list of errors.
  127. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  128. // A middleware can be used to collect all the errors
  129. // and push them to a database together, print a log, or append it in the HTTP response.
  130. func (c *Context) Error(err error) *Error {
  131. var parsedError *Error
  132. switch err.(type) {
  133. case *Error:
  134. parsedError = err.(*Error)
  135. default:
  136. parsedError = &Error{
  137. Err: err,
  138. Type: ErrorTypePrivate,
  139. }
  140. }
  141. c.Errors = append(c.Errors, parsedError)
  142. return parsedError
  143. }
  144. /************************************/
  145. /******** METADATA MANAGEMENT********/
  146. /************************************/
  147. // Set is used to store a new key/value pair exclusively for this context.
  148. // It also lazy initializes c.Keys if it was not used previously.
  149. func (c *Context) Set(key string, value interface{}) {
  150. if c.Keys == nil {
  151. c.Keys = make(map[string]interface{})
  152. }
  153. c.Keys[key] = value
  154. }
  155. // Get returns the value for the given key, ie: (value, true).
  156. // If the value does not exists it returns (nil, false)
  157. func (c *Context) Get(key string) (value interface{}, exists bool) {
  158. value, exists = c.Keys[key]
  159. return
  160. }
  161. // MustGet returns the value for the given key if it exists, otherwise it panics.
  162. func (c *Context) MustGet(key string) interface{} {
  163. if value, exists := c.Get(key); exists {
  164. return value
  165. }
  166. panic("Key \"" + key + "\" does not exist")
  167. }
  168. // GetString returns the value associated with the key as a string.
  169. func (c *Context) GetString(key string) (s string) {
  170. if val, ok := c.Get(key); ok && val != nil {
  171. s, _ = val.(string)
  172. }
  173. return
  174. }
  175. // GetBool returns the value associated with the key as a boolean.
  176. func (c *Context) GetBool(key string) (b bool) {
  177. if val, ok := c.Get(key); ok && val != nil {
  178. b, _ = val.(bool)
  179. }
  180. return
  181. }
  182. // GetInt returns the value associated with the key as an integer.
  183. func (c *Context) GetInt(key string) (i int) {
  184. if val, ok := c.Get(key); ok && val != nil {
  185. i, _ = val.(int)
  186. }
  187. return
  188. }
  189. // GetInt64 returns the value associated with the key as an integer.
  190. func (c *Context) GetInt64(key string) (i64 int64) {
  191. if val, ok := c.Get(key); ok && val != nil {
  192. i64, _ = val.(int64)
  193. }
  194. return
  195. }
  196. // GetFloat64 returns the value associated with the key as a float64.
  197. func (c *Context) GetFloat64(key string) (f64 float64) {
  198. if val, ok := c.Get(key); ok && val != nil {
  199. f64, _ = val.(float64)
  200. }
  201. return
  202. }
  203. // GetTime returns the value associated with the key as time.
  204. func (c *Context) GetTime(key string) (t time.Time) {
  205. if val, ok := c.Get(key); ok && val != nil {
  206. t, _ = val.(time.Time)
  207. }
  208. return
  209. }
  210. // GetDuration returns the value associated with the key as a duration.
  211. func (c *Context) GetDuration(key string) (d time.Duration) {
  212. if val, ok := c.Get(key); ok && val != nil {
  213. d, _ = val.(time.Duration)
  214. }
  215. return
  216. }
  217. // GetStringSlice returns the value associated with the key as a slice of strings.
  218. func (c *Context) GetStringSlice(key string) (ss []string) {
  219. if val, ok := c.Get(key); ok && val != nil {
  220. ss, _ = val.([]string)
  221. }
  222. return
  223. }
  224. // GetStringMap returns the value associated with the key as a map of interfaces.
  225. func (c *Context) GetStringMap(key string) (sm map[string]interface{}) {
  226. if val, ok := c.Get(key); ok && val != nil {
  227. sm, _ = val.(map[string]interface{})
  228. }
  229. return
  230. }
  231. // GetStringMapString returns the value associated with the key as a map of strings.
  232. func (c *Context) GetStringMapString(key string) (sms map[string]string) {
  233. if val, ok := c.Get(key); ok && val != nil {
  234. sms, _ = val.(map[string]string)
  235. }
  236. return
  237. }
  238. // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
  239. func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) {
  240. if val, ok := c.Get(key); ok && val != nil {
  241. smss, _ = val.(map[string][]string)
  242. }
  243. return
  244. }
  245. /************************************/
  246. /************ INPUT DATA ************/
  247. /************************************/
  248. // Param returns the value of the URL param.
  249. // It is a shortcut for c.Params.ByName(key)
  250. // router.GET("/user/:id", func(c *gin.Context) {
  251. // // a GET request to /user/john
  252. // id := c.Param("id") // id == "john"
  253. // })
  254. func (c *Context) Param(key string) string {
  255. return c.Params.ByName(key)
  256. }
  257. // Query returns the keyed url query value if it exists,
  258. // otherwise it returns an empty string `("")`.
  259. // It is shortcut for `c.Request.URL.Query().Get(key)`
  260. // GET /path?id=1234&name=Manu&value=
  261. // c.Query("id") == "1234"
  262. // c.Query("name") == "Manu"
  263. // c.Query("value") == ""
  264. // c.Query("wtf") == ""
  265. func (c *Context) Query(key string) string {
  266. value, _ := c.GetQuery(key)
  267. return value
  268. }
  269. // DefaultQuery returns the keyed url query value if it exists,
  270. // otherwise it returns the specified defaultValue string.
  271. // See: Query() and GetQuery() for further information.
  272. // GET /?name=Manu&lastname=
  273. // c.DefaultQuery("name", "unknown") == "Manu"
  274. // c.DefaultQuery("id", "none") == "none"
  275. // c.DefaultQuery("lastname", "none") == ""
  276. func (c *Context) DefaultQuery(key, defaultValue string) string {
  277. if value, ok := c.GetQuery(key); ok {
  278. return value
  279. }
  280. return defaultValue
  281. }
  282. // GetQuery is like Query(), it returns the keyed url query value
  283. // if it exists `(value, true)` (even when the value is an empty string),
  284. // otherwise it returns `("", false)`.
  285. // It is shortcut for `c.Request.URL.Query().Get(key)`
  286. // GET /?name=Manu&lastname=
  287. // ("Manu", true) == c.GetQuery("name")
  288. // ("", false) == c.GetQuery("id")
  289. // ("", true) == c.GetQuery("lastname")
  290. func (c *Context) GetQuery(key string) (string, bool) {
  291. if values, ok := c.GetQueryArray(key); ok {
  292. return values[0], ok
  293. }
  294. return "", false
  295. }
  296. // QueryArray returns a slice of strings for a given query key.
  297. // The length of the slice depends on the number of params with the given key.
  298. func (c *Context) QueryArray(key string) []string {
  299. values, _ := c.GetQueryArray(key)
  300. return values
  301. }
  302. // GetQueryArray returns a slice of strings for a given query key, plus
  303. // a boolean value whether at least one value exists for the given key.
  304. func (c *Context) GetQueryArray(key string) ([]string, bool) {
  305. req := c.Request
  306. if values, ok := req.URL.Query()[key]; ok && len(values) > 0 {
  307. return values, true
  308. }
  309. return []string{}, false
  310. }
  311. // PostForm returns the specified key from a POST urlencoded form or multipart form
  312. // when it exists, otherwise it returns an empty string `("")`.
  313. func (c *Context) PostForm(key string) string {
  314. value, _ := c.GetPostForm(key)
  315. return value
  316. }
  317. // DefaultPostForm returns the specified key from a POST urlencoded form or multipart form
  318. // when it exists, otherwise it returns the specified defaultValue string.
  319. // See: PostForm() and GetPostForm() for further information.
  320. func (c *Context) DefaultPostForm(key, defaultValue string) string {
  321. if value, ok := c.GetPostForm(key); ok {
  322. return value
  323. }
  324. return defaultValue
  325. }
  326. // GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded
  327. // form or multipart form when it exists `(value, true)` (even when the value is an empty string),
  328. // otherwise it returns ("", false).
  329. // For example, during a PATCH request to update the user's email:
  330. // email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
  331. // email= --> ("", true) := GetPostForm("email") // set email to ""
  332. // --> ("", false) := GetPostForm("email") // do nothing with email
  333. func (c *Context) GetPostForm(key string) (string, bool) {
  334. if values, ok := c.GetPostFormArray(key); ok {
  335. return values[0], ok
  336. }
  337. return "", false
  338. }
  339. // PostFormArray returns a slice of strings for a given form key.
  340. // The length of the slice depends on the number of params with the given key.
  341. func (c *Context) PostFormArray(key string) []string {
  342. values, _ := c.GetPostFormArray(key)
  343. return values
  344. }
  345. // GetPostFormArray returns a slice of strings for a given form key, plus
  346. // a boolean value whether at least one value exists for the given key.
  347. func (c *Context) GetPostFormArray(key string) ([]string, bool) {
  348. req := c.Request
  349. req.ParseForm()
  350. req.ParseMultipartForm(defaultMemory)
  351. if values := req.PostForm[key]; len(values) > 0 {
  352. return values, true
  353. }
  354. if req.MultipartForm != nil && req.MultipartForm.File != nil {
  355. if values := req.MultipartForm.Value[key]; len(values) > 0 {
  356. return values, true
  357. }
  358. }
  359. return []string{}, false
  360. }
  361. // FormFile returns the first file for the provided form key.
  362. func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
  363. _, fh, err := c.Request.FormFile(name)
  364. return fh, err
  365. }
  366. // MultipartForm is the parsed multipart form, including file uploads.
  367. func (c *Context) MultipartForm() (*multipart.Form, error) {
  368. err := c.Request.ParseMultipartForm(defaultMemory)
  369. return c.Request.MultipartForm, err
  370. }
  371. // Bind checks the Content-Type to select a binding engine automatically,
  372. // Depending the "Content-Type" header different bindings are used:
  373. // "application/json" --> JSON binding
  374. // "application/xml" --> XML binding
  375. // otherwise --> returns an error
  376. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
  377. // It decodes the json payload into the struct specified as a pointer.
  378. // Like ParseBody() but this method also writes a 400 error if the json is not valid.
  379. func (c *Context) Bind(obj interface{}) error {
  380. b := binding.Default(c.Request.Method, c.ContentType())
  381. return c.MustBindWith(obj, b)
  382. }
  383. // BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON)
  384. func (c *Context) BindJSON(obj interface{}) error {
  385. return c.MustBindWith(obj, binding.JSON)
  386. }
  387. // MustBindWith binds the passed struct pointer using the specified binding
  388. // engine. It will abort the request with HTTP 400 if any error ocurrs.
  389. // See the binding package.
  390. func (c *Context) MustBindWith(obj interface{}, b binding.Binding) (err error) {
  391. if err = c.ShouldBindWith(obj, b); err != nil {
  392. c.AbortWithError(400, err).SetType(ErrorTypeBind)
  393. }
  394. return
  395. }
  396. // ShouldBindWith binds the passed struct pointer using the specified binding
  397. // engine.
  398. // See the binding package.
  399. func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {
  400. return b.Bind(c.Request, obj)
  401. }
  402. // ClientIP implements a best effort algorithm to return the real client IP, it parses
  403. // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
  404. // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
  405. func (c *Context) ClientIP() string {
  406. if c.engine.ForwardedByClientIP {
  407. clientIP := c.requestHeader("X-Forwarded-For")
  408. if index := strings.IndexByte(clientIP, ','); index >= 0 {
  409. clientIP = clientIP[0:index]
  410. }
  411. clientIP = strings.TrimSpace(clientIP)
  412. if len(clientIP) > 0 {
  413. return clientIP
  414. }
  415. clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
  416. if len(clientIP) > 0 {
  417. return clientIP
  418. }
  419. }
  420. if c.engine.AppEngine {
  421. if addr := c.Request.Header.Get("X-Appengine-Remote-Addr"); addr != "" {
  422. return addr
  423. }
  424. }
  425. if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
  426. return ip
  427. }
  428. return ""
  429. }
  430. // ContentType returns the Content-Type header of the request.
  431. func (c *Context) ContentType() string {
  432. return filterFlags(c.requestHeader("Content-Type"))
  433. }
  434. // IsWebsocket returns true if the request headers indicate that a websocket
  435. // handshake is being initiated by the client.
  436. func (c *Context) IsWebsocket() bool {
  437. if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
  438. strings.ToLower(c.requestHeader("Upgrade")) == "websocket" {
  439. return true
  440. }
  441. return false
  442. }
  443. func (c *Context) requestHeader(key string) string {
  444. if values, _ := c.Request.Header[key]; len(values) > 0 {
  445. return values[0]
  446. }
  447. return ""
  448. }
  449. /************************************/
  450. /******** RESPONSE RENDERING ********/
  451. /************************************/
  452. // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function
  453. func bodyAllowedForStatus(status int) bool {
  454. switch {
  455. case status >= 100 && status <= 199:
  456. return false
  457. case status == 204:
  458. return false
  459. case status == 304:
  460. return false
  461. }
  462. return true
  463. }
  464. func (c *Context) Status(code int) {
  465. c.writermem.WriteHeader(code)
  466. }
  467. // Header is a intelligent shortcut for c.Writer.Header().Set(key, value)
  468. // It writes a header in the response.
  469. // If value == "", this method removes the header `c.Writer.Header().Del(key)`
  470. func (c *Context) Header(key, value string) {
  471. if len(value) == 0 {
  472. c.Writer.Header().Del(key)
  473. } else {
  474. c.Writer.Header().Set(key, value)
  475. }
  476. }
  477. // GetHeader returns value from request headers
  478. func (c *Context) GetHeader(key string) string {
  479. return c.requestHeader(key)
  480. }
  481. // GetRawData return stream data
  482. func (c *Context) GetRawData() ([]byte, error) {
  483. return ioutil.ReadAll(c.Request.Body)
  484. }
  485. func (c *Context) SetCookie(
  486. name string,
  487. value string,
  488. maxAge int,
  489. path string,
  490. domain string,
  491. secure bool,
  492. httpOnly bool,
  493. ) {
  494. if path == "" {
  495. path = "/"
  496. }
  497. http.SetCookie(c.Writer, &http.Cookie{
  498. Name: name,
  499. Value: url.QueryEscape(value),
  500. MaxAge: maxAge,
  501. Path: path,
  502. Domain: domain,
  503. Secure: secure,
  504. HttpOnly: httpOnly,
  505. })
  506. }
  507. func (c *Context) Cookie(name string) (string, error) {
  508. cookie, err := c.Request.Cookie(name)
  509. if err != nil {
  510. return "", err
  511. }
  512. val, _ := url.QueryUnescape(cookie.Value)
  513. return val, nil
  514. }
  515. func (c *Context) Render(code int, r render.Render) {
  516. c.Status(code)
  517. if !bodyAllowedForStatus(code) {
  518. r.WriteContentType(c.Writer)
  519. c.Writer.WriteHeaderNow()
  520. return
  521. }
  522. if err := r.Render(c.Writer); err != nil {
  523. panic(err)
  524. }
  525. }
  526. // HTML renders the HTTP template specified by its file name.
  527. // It also updates the HTTP code and sets the Content-Type as "text/html".
  528. // See http://golang.org/doc/articles/wiki/
  529. func (c *Context) HTML(code int, name string, obj interface{}) {
  530. instance := c.engine.HTMLRender.Instance(name, obj)
  531. c.Render(code, instance)
  532. }
  533. // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
  534. // It also sets the Content-Type as "application/json".
  535. // WARNING: we recommend to use this only for development purposes since printing pretty JSON is
  536. // more CPU and bandwidth consuming. Use Context.JSON() instead.
  537. func (c *Context) IndentedJSON(code int, obj interface{}) {
  538. c.Render(code, render.IndentedJSON{Data: obj})
  539. }
  540. // JSON serializes the given struct as JSON into the response body.
  541. // It also sets the Content-Type as "application/json".
  542. func (c *Context) JSON(code int, obj interface{}) {
  543. c.Render(code, render.JSON{Data: obj})
  544. }
  545. // XML serializes the given struct as XML into the response body.
  546. // It also sets the Content-Type as "application/xml".
  547. func (c *Context) XML(code int, obj interface{}) {
  548. c.Render(code, render.XML{Data: obj})
  549. }
  550. // YAML serializes the given struct as YAML into the response body.
  551. func (c *Context) YAML(code int, obj interface{}) {
  552. c.Render(code, render.YAML{Data: obj})
  553. }
  554. // String writes the given string into the response body.
  555. func (c *Context) String(code int, format string, values ...interface{}) {
  556. c.Render(code, render.String{Format: format, Data: values})
  557. }
  558. // Redirect returns a HTTP redirect to the specific location.
  559. func (c *Context) Redirect(code int, location string) {
  560. c.Render(-1, render.Redirect{
  561. Code: code,
  562. Location: location,
  563. Request: c.Request,
  564. })
  565. }
  566. // Data writes some data into the body stream and updates the HTTP code.
  567. func (c *Context) Data(code int, contentType string, data []byte) {
  568. c.Render(code, render.Data{
  569. ContentType: contentType,
  570. Data: data,
  571. })
  572. }
  573. // File writes the specified file into the body stream in a efficient way.
  574. func (c *Context) File(filepath string) {
  575. http.ServeFile(c.Writer, c.Request, filepath)
  576. }
  577. // SSEvent writes a Server-Sent Event into the body stream.
  578. func (c *Context) SSEvent(name string, message interface{}) {
  579. c.Render(-1, sse.Event{
  580. Event: name,
  581. Data: message,
  582. })
  583. }
  584. func (c *Context) Stream(step func(w io.Writer) bool) {
  585. w := c.Writer
  586. clientGone := w.CloseNotify()
  587. for {
  588. select {
  589. case <-clientGone:
  590. return
  591. default:
  592. keepOpen := step(w)
  593. w.Flush()
  594. if !keepOpen {
  595. return
  596. }
  597. }
  598. }
  599. }
  600. /************************************/
  601. /******** CONTENT NEGOTIATION *******/
  602. /************************************/
  603. type Negotiate struct {
  604. Offered []string
  605. HTMLName string
  606. HTMLData interface{}
  607. JSONData interface{}
  608. XMLData interface{}
  609. Data interface{}
  610. }
  611. func (c *Context) Negotiate(code int, config Negotiate) {
  612. switch c.NegotiateFormat(config.Offered...) {
  613. case binding.MIMEJSON:
  614. data := chooseData(config.JSONData, config.Data)
  615. c.JSON(code, data)
  616. case binding.MIMEHTML:
  617. data := chooseData(config.HTMLData, config.Data)
  618. c.HTML(code, config.HTMLName, data)
  619. case binding.MIMEXML:
  620. data := chooseData(config.XMLData, config.Data)
  621. c.XML(code, data)
  622. default:
  623. c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  624. }
  625. }
  626. func (c *Context) NegotiateFormat(offered ...string) string {
  627. assert1(len(offered) > 0, "you must provide at least one offer")
  628. if c.Accepted == nil {
  629. c.Accepted = parseAccept(c.requestHeader("Accept"))
  630. }
  631. if len(c.Accepted) == 0 {
  632. return offered[0]
  633. }
  634. for _, accepted := range c.Accepted {
  635. for _, offert := range offered {
  636. if accepted == offert {
  637. return offert
  638. }
  639. }
  640. }
  641. return ""
  642. }
  643. func (c *Context) SetAccepted(formats ...string) {
  644. c.Accepted = formats
  645. }
  646. /************************************/
  647. /***** GOLANG.ORG/X/NET/CONTEXT *****/
  648. /************************************/
  649. func (c *Context) Deadline() (deadline time.Time, ok bool) {
  650. return
  651. }
  652. func (c *Context) Done() <-chan struct{} {
  653. return nil
  654. }
  655. func (c *Context) Err() error {
  656. return nil
  657. }
  658. func (c *Context) Value(key interface{}) interface{} {
  659. if key == 0 {
  660. return c.Request
  661. }
  662. if keyAsString, ok := key.(string); ok {
  663. val, _ := c.Get(keyAsString)
  664. return val
  665. }
  666. return nil
  667. }