context.go 32 KB

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