context.go 32 KB

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