context.go 24 KB

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