context.go 27 KB

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