context.go 33 KB

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