context.go 36 KB

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