context.go 31 KB

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