context.go 31 KB

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