context.go 31 KB

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