context.go 25 KB

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