context.go 23 KB

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