context.go 27 KB

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