context.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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-gonic/gin/binding"
  17. "github.com/gin-gonic/gin/render"
  18. "gopkg.in/gin-contrib/sse.v0"
  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.BindWith(obj, b)
  382. }
  383. // BindJSON is a shortcut for c.BindWith(obj, binding.JSON)
  384. func (c *Context) BindJSON(obj interface{}) error {
  385. return c.BindWith(obj, binding.JSON)
  386. }
  387. // BindWith binds the passed struct pointer using the specified binding engine.
  388. // See the binding package.
  389. func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
  390. if err := b.Bind(c.Request, obj); err != nil {
  391. c.AbortWithError(400, err).SetType(ErrorTypeBind)
  392. return err
  393. }
  394. return nil
  395. }
  396. // ClientIP implements a best effort algorithm to return the real client IP, it parses
  397. // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
  398. // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
  399. func (c *Context) ClientIP() string {
  400. if c.engine.ForwardedByClientIP {
  401. clientIP := c.requestHeader("X-Forwarded-For")
  402. if index := strings.IndexByte(clientIP, ','); index >= 0 {
  403. clientIP = clientIP[0:index]
  404. }
  405. clientIP = strings.TrimSpace(clientIP)
  406. if len(clientIP) > 0 {
  407. return clientIP
  408. }
  409. clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
  410. if len(clientIP) > 0 {
  411. return clientIP
  412. }
  413. }
  414. if c.engine.AppEngine {
  415. if addr := c.Request.Header.Get("X-Appengine-Remote-Addr"); addr != "" {
  416. return addr
  417. }
  418. }
  419. if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
  420. return ip
  421. }
  422. return ""
  423. }
  424. // ContentType returns the Content-Type header of the request.
  425. func (c *Context) ContentType() string {
  426. return filterFlags(c.requestHeader("Content-Type"))
  427. }
  428. // IsWebsocket returns true if the request headers indicate that a websocket
  429. // handshake is being initiated by the client.
  430. func (c *Context) IsWebsocket() bool {
  431. if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
  432. strings.ToLower(c.requestHeader("Upgrade")) == "websocket" {
  433. return true
  434. }
  435. return false
  436. }
  437. func (c *Context) requestHeader(key string) string {
  438. if values, _ := c.Request.Header[key]; len(values) > 0 {
  439. return values[0]
  440. }
  441. return ""
  442. }
  443. /************************************/
  444. /******** RESPONSE RENDERING ********/
  445. /************************************/
  446. // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function
  447. func bodyAllowedForStatus(status int) bool {
  448. switch {
  449. case status >= 100 && status <= 199:
  450. return false
  451. case status == 204:
  452. return false
  453. case status == 304:
  454. return false
  455. }
  456. return true
  457. }
  458. func (c *Context) Status(code int) {
  459. c.writermem.WriteHeader(code)
  460. }
  461. // Header is a intelligent shortcut for c.Writer.Header().Set(key, value)
  462. // It writes a header in the response.
  463. // If value == "", this method removes the header `c.Writer.Header().Del(key)`
  464. func (c *Context) Header(key, value string) {
  465. if len(value) == 0 {
  466. c.Writer.Header().Del(key)
  467. } else {
  468. c.Writer.Header().Set(key, value)
  469. }
  470. }
  471. // GetHeader returns value from request headers
  472. func (c *Context) GetHeader(key string) string {
  473. return c.requestHeader(key)
  474. }
  475. // GetRawData return stream data
  476. func (c *Context) GetRawData() ([]byte, error) {
  477. return ioutil.ReadAll(c.Request.Body)
  478. }
  479. func (c *Context) SetCookie(
  480. name string,
  481. value string,
  482. maxAge int,
  483. path string,
  484. domain string,
  485. secure bool,
  486. httpOnly bool,
  487. ) {
  488. if path == "" {
  489. path = "/"
  490. }
  491. http.SetCookie(c.Writer, &http.Cookie{
  492. Name: name,
  493. Value: url.QueryEscape(value),
  494. MaxAge: maxAge,
  495. Path: path,
  496. Domain: domain,
  497. Secure: secure,
  498. HttpOnly: httpOnly,
  499. })
  500. }
  501. func (c *Context) Cookie(name string) (string, error) {
  502. cookie, err := c.Request.Cookie(name)
  503. if err != nil {
  504. return "", err
  505. }
  506. val, _ := url.QueryUnescape(cookie.Value)
  507. return val, nil
  508. }
  509. func (c *Context) Render(code int, r render.Render) {
  510. c.Status(code)
  511. if !bodyAllowedForStatus(code) {
  512. r.WriteContentType(c.Writer)
  513. c.Writer.WriteHeaderNow()
  514. return
  515. }
  516. if err := r.Render(c.Writer); err != nil {
  517. panic(err)
  518. }
  519. }
  520. // HTML renders the HTTP template specified by its file name.
  521. // It also updates the HTTP code and sets the Content-Type as "text/html".
  522. // See http://golang.org/doc/articles/wiki/
  523. func (c *Context) HTML(code int, name string, obj interface{}) {
  524. instance := c.engine.HTMLRender.Instance(name, obj)
  525. c.Render(code, instance)
  526. }
  527. // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
  528. // It also sets the Content-Type as "application/json".
  529. // WARNING: we recommend to use this only for development purposes since printing pretty JSON is
  530. // more CPU and bandwidth consuming. Use Context.JSON() instead.
  531. func (c *Context) IndentedJSON(code int, obj interface{}) {
  532. c.Render(code, render.IndentedJSON{Data: obj})
  533. }
  534. // JSON serializes the given struct as JSON into the response body.
  535. // It also sets the Content-Type as "application/json".
  536. func (c *Context) JSON(code int, obj interface{}) {
  537. c.Render(code, render.JSON{Data: obj})
  538. }
  539. // XML serializes the given struct as XML into the response body.
  540. // It also sets the Content-Type as "application/xml".
  541. func (c *Context) XML(code int, obj interface{}) {
  542. c.Render(code, render.XML{Data: obj})
  543. }
  544. // YAML serializes the given struct as YAML into the response body.
  545. func (c *Context) YAML(code int, obj interface{}) {
  546. c.Render(code, render.YAML{Data: obj})
  547. }
  548. // String writes the given string into the response body.
  549. func (c *Context) String(code int, format string, values ...interface{}) {
  550. c.Render(code, render.String{Format: format, Data: values})
  551. }
  552. // Redirect returns a HTTP redirect to the specific location.
  553. func (c *Context) Redirect(code int, location string) {
  554. c.Render(-1, render.Redirect{
  555. Code: code,
  556. Location: location,
  557. Request: c.Request,
  558. })
  559. }
  560. // Data writes some data into the body stream and updates the HTTP code.
  561. func (c *Context) Data(code int, contentType string, data []byte) {
  562. c.Render(code, render.Data{
  563. ContentType: contentType,
  564. Data: data,
  565. })
  566. }
  567. // File writes the specified file into the body stream in a efficient way.
  568. func (c *Context) File(filepath string) {
  569. http.ServeFile(c.Writer, c.Request, filepath)
  570. }
  571. // SSEvent writes a Server-Sent Event into the body stream.
  572. func (c *Context) SSEvent(name string, message interface{}) {
  573. c.Render(-1, sse.Event{
  574. Event: name,
  575. Data: message,
  576. })
  577. }
  578. func (c *Context) Stream(step func(w io.Writer) bool) {
  579. w := c.Writer
  580. clientGone := w.CloseNotify()
  581. for {
  582. select {
  583. case <-clientGone:
  584. return
  585. default:
  586. keepOpen := step(w)
  587. w.Flush()
  588. if !keepOpen {
  589. return
  590. }
  591. }
  592. }
  593. }
  594. /************************************/
  595. /******** CONTENT NEGOTIATION *******/
  596. /************************************/
  597. type Negotiate struct {
  598. Offered []string
  599. HTMLName string
  600. HTMLData interface{}
  601. JSONData interface{}
  602. XMLData interface{}
  603. Data interface{}
  604. }
  605. func (c *Context) Negotiate(code int, config Negotiate) {
  606. switch c.NegotiateFormat(config.Offered...) {
  607. case binding.MIMEJSON:
  608. data := chooseData(config.JSONData, config.Data)
  609. c.JSON(code, data)
  610. case binding.MIMEHTML:
  611. data := chooseData(config.HTMLData, config.Data)
  612. c.HTML(code, config.HTMLName, data)
  613. case binding.MIMEXML:
  614. data := chooseData(config.XMLData, config.Data)
  615. c.XML(code, data)
  616. default:
  617. c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  618. }
  619. }
  620. func (c *Context) NegotiateFormat(offered ...string) string {
  621. assert1(len(offered) > 0, "you must provide at least one offer")
  622. if c.Accepted == nil {
  623. c.Accepted = parseAccept(c.requestHeader("Accept"))
  624. }
  625. if len(c.Accepted) == 0 {
  626. return offered[0]
  627. }
  628. for _, accepted := range c.Accepted {
  629. for _, offert := range offered {
  630. if accepted == offert {
  631. return offert
  632. }
  633. }
  634. }
  635. return ""
  636. }
  637. func (c *Context) SetAccepted(formats ...string) {
  638. c.Accepted = formats
  639. }
  640. /************************************/
  641. /***** GOLANG.ORG/X/NET/CONTEXT *****/
  642. /************************************/
  643. func (c *Context) Deadline() (deadline time.Time, ok bool) {
  644. return
  645. }
  646. func (c *Context) Done() <-chan struct{} {
  647. return nil
  648. }
  649. func (c *Context) Err() error {
  650. return nil
  651. }
  652. func (c *Context) Value(key interface{}) interface{} {
  653. if key == 0 {
  654. return c.Request
  655. }
  656. if keyAsString, ok := key.(string); ok {
  657. val, _ := c.Get(keyAsString)
  658. return val
  659. }
  660. return nil
  661. }