context.go 30 KB

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