context.go 33 KB

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