context.go 37 KB

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