context.go 33 KB

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