context.go 38 KB

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