context.go 22 KB

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