context.go 32 KB

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