context.go 23 KB

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