context.go 37 KB

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