context.go 32 KB

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