context.go 33 KB

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