context.go 23 KB

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