context.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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.ParseForm()
  362. req.ParseMultipartForm(c.engine.MaxMultipartMemory)
  363. if values := req.PostForm[key]; len(values) > 0 {
  364. return values, true
  365. }
  366. if req.MultipartForm != nil && req.MultipartForm.File != nil {
  367. if values := req.MultipartForm.Value[key]; len(values) > 0 {
  368. return values, true
  369. }
  370. }
  371. return []string{}, false
  372. }
  373. // PostFormMap returns a map for a given form key.
  374. func (c *Context) PostFormMap(key string) map[string]string {
  375. dicts, _ := c.GetPostFormMap(key)
  376. return dicts
  377. }
  378. // GetPostFormMap returns a map for a given form key, plus a boolean value
  379. // whether at least one value exists for the given key.
  380. func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {
  381. req := c.Request
  382. req.ParseForm()
  383. req.ParseMultipartForm(c.engine.MaxMultipartMemory)
  384. dicts, exist := c.get(req.PostForm, key)
  385. if !exist && req.MultipartForm != nil && req.MultipartForm.File != nil {
  386. dicts, exist = c.get(req.MultipartForm.Value, key)
  387. }
  388. return dicts, exist
  389. }
  390. // get is an internal method and returns a map which satisfy conditions.
  391. func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) {
  392. dicts := make(map[string]string)
  393. exist := false
  394. for k, v := range m {
  395. if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key {
  396. if j := strings.IndexByte(k[i+1:], ']'); j >= 1 {
  397. exist = true
  398. dicts[k[i+1:][:j]] = v[0]
  399. }
  400. }
  401. }
  402. return dicts, exist
  403. }
  404. // FormFile returns the first file for the provided form key.
  405. func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
  406. _, fh, err := c.Request.FormFile(name)
  407. return fh, err
  408. }
  409. // MultipartForm is the parsed multipart form, including file uploads.
  410. func (c *Context) MultipartForm() (*multipart.Form, error) {
  411. err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)
  412. return c.Request.MultipartForm, err
  413. }
  414. // SaveUploadedFile uploads the form file to specific dst.
  415. func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
  416. src, err := file.Open()
  417. if err != nil {
  418. return err
  419. }
  420. defer src.Close()
  421. out, err := os.Create(dst)
  422. if err != nil {
  423. return err
  424. }
  425. defer out.Close()
  426. io.Copy(out, src)
  427. return nil
  428. }
  429. // Bind checks the Content-Type to select a binding engine automatically,
  430. // Depending the "Content-Type" header different bindings are used:
  431. // "application/json" --> JSON binding
  432. // "application/xml" --> XML binding
  433. // otherwise --> returns an error.
  434. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
  435. // It decodes the json payload into the struct specified as a pointer.
  436. // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
  437. func (c *Context) Bind(obj interface{}) error {
  438. b := binding.Default(c.Request.Method, c.ContentType())
  439. return c.MustBindWith(obj, b)
  440. }
  441. // BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
  442. func (c *Context) BindJSON(obj interface{}) error {
  443. return c.MustBindWith(obj, binding.JSON)
  444. }
  445. // BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML).
  446. func (c *Context) BindXML(obj interface{}) error {
  447. return c.MustBindWith(obj, binding.XML)
  448. }
  449. // BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).
  450. func (c *Context) BindQuery(obj interface{}) error {
  451. return c.MustBindWith(obj, binding.Query)
  452. }
  453. // MustBindWith binds the passed struct pointer using the specified binding engine.
  454. // It will abort the request with HTTP 400 if any error ocurrs.
  455. // See the binding package.
  456. func (c *Context) MustBindWith(obj interface{}, b binding.Binding) (err error) {
  457. if err = c.ShouldBindWith(obj, b); err != nil {
  458. c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind)
  459. }
  460. return
  461. }
  462. // ShouldBind checks the Content-Type to select a binding engine automatically,
  463. // Depending the "Content-Type" header different bindings are used:
  464. // "application/json" --> JSON binding
  465. // "application/xml" --> XML binding
  466. // otherwise --> returns an error
  467. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
  468. // It decodes the json payload into the struct specified as a pointer.
  469. // Like c.Bind() but this method does not set the response status code to 400 and abort if the json is not valid.
  470. func (c *Context) ShouldBind(obj interface{}) error {
  471. b := binding.Default(c.Request.Method, c.ContentType())
  472. return c.ShouldBindWith(obj, b)
  473. }
  474. // ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
  475. func (c *Context) ShouldBindJSON(obj interface{}) error {
  476. return c.ShouldBindWith(obj, binding.JSON)
  477. }
  478. // ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).
  479. func (c *Context) ShouldBindXML(obj interface{}) error {
  480. return c.ShouldBindWith(obj, binding.XML)
  481. }
  482. // ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).
  483. func (c *Context) ShouldBindQuery(obj interface{}) error {
  484. return c.ShouldBindWith(obj, binding.Query)
  485. }
  486. // ShouldBindWith binds the passed struct pointer using the specified binding engine.
  487. // See the binding package.
  488. func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {
  489. return b.Bind(c.Request, obj)
  490. }
  491. // ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
  492. // body into the context, and reuse when it is called again.
  493. //
  494. // NOTE: This method reads the body before binding. So you should use
  495. // ShouldBindWith for better performance if you need to call only once.
  496. func (c *Context) ShouldBindBodyWith(
  497. obj interface{}, bb binding.BindingBody,
  498. ) (err error) {
  499. var body []byte
  500. if cb, ok := c.Get(BodyBytesKey); ok {
  501. if cbb, ok := cb.([]byte); ok {
  502. body = cbb
  503. }
  504. }
  505. if body == nil {
  506. body, err = ioutil.ReadAll(c.Request.Body)
  507. if err != nil {
  508. return err
  509. }
  510. c.Set(BodyBytesKey, body)
  511. }
  512. return bb.BindBody(body, obj)
  513. }
  514. // ClientIP implements a best effort algorithm to return the real client IP, it parses
  515. // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
  516. // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
  517. func (c *Context) ClientIP() string {
  518. if c.engine.ForwardedByClientIP {
  519. clientIP := c.requestHeader("X-Forwarded-For")
  520. clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
  521. if clientIP == "" {
  522. clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
  523. }
  524. if clientIP != "" {
  525. return clientIP
  526. }
  527. }
  528. if c.engine.AppEngine {
  529. if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" {
  530. return addr
  531. }
  532. }
  533. if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
  534. return ip
  535. }
  536. return ""
  537. }
  538. // ContentType returns the Content-Type header of the request.
  539. func (c *Context) ContentType() string {
  540. return filterFlags(c.requestHeader("Content-Type"))
  541. }
  542. // IsWebsocket returns true if the request headers indicate that a websocket
  543. // handshake is being initiated by the client.
  544. func (c *Context) IsWebsocket() bool {
  545. if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
  546. strings.ToLower(c.requestHeader("Upgrade")) == "websocket" {
  547. return true
  548. }
  549. return false
  550. }
  551. func (c *Context) requestHeader(key string) string {
  552. return c.Request.Header.Get(key)
  553. }
  554. /************************************/
  555. /******** RESPONSE RENDERING ********/
  556. /************************************/
  557. // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
  558. func bodyAllowedForStatus(status int) bool {
  559. switch {
  560. case status >= 100 && status <= 199:
  561. return false
  562. case status == http.StatusNoContent:
  563. return false
  564. case status == http.StatusNotModified:
  565. return false
  566. }
  567. return true
  568. }
  569. // Status sets the HTTP response code.
  570. func (c *Context) Status(code int) {
  571. c.writermem.WriteHeader(code)
  572. }
  573. // Header is a intelligent shortcut for c.Writer.Header().Set(key, value).
  574. // It writes a header in the response.
  575. // If value == "", this method removes the header `c.Writer.Header().Del(key)`
  576. func (c *Context) Header(key, value string) {
  577. if value == "" {
  578. c.Writer.Header().Del(key)
  579. return
  580. }
  581. c.Writer.Header().Set(key, value)
  582. }
  583. // GetHeader returns value from request headers.
  584. func (c *Context) GetHeader(key string) string {
  585. return c.requestHeader(key)
  586. }
  587. // GetRawData return stream data.
  588. func (c *Context) GetRawData() ([]byte, error) {
  589. return ioutil.ReadAll(c.Request.Body)
  590. }
  591. // SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
  592. // The provided cookie must have a valid Name. Invalid cookies may be
  593. // silently dropped.
  594. func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
  595. if path == "" {
  596. path = "/"
  597. }
  598. http.SetCookie(c.Writer, &http.Cookie{
  599. Name: name,
  600. Value: url.QueryEscape(value),
  601. MaxAge: maxAge,
  602. Path: path,
  603. Domain: domain,
  604. Secure: secure,
  605. HttpOnly: httpOnly,
  606. })
  607. }
  608. // Cookie returns the named cookie provided in the request or
  609. // ErrNoCookie if not found. And return the named cookie is unescaped.
  610. // If multiple cookies match the given name, only one cookie will
  611. // be returned.
  612. func (c *Context) Cookie(name string) (string, error) {
  613. cookie, err := c.Request.Cookie(name)
  614. if err != nil {
  615. return "", err
  616. }
  617. val, _ := url.QueryUnescape(cookie.Value)
  618. return val, nil
  619. }
  620. // Render writes the response headers and calls render.Render to render data.
  621. func (c *Context) Render(code int, r render.Render) {
  622. c.Status(code)
  623. if !bodyAllowedForStatus(code) {
  624. r.WriteContentType(c.Writer)
  625. c.Writer.WriteHeaderNow()
  626. return
  627. }
  628. if err := r.Render(c.Writer); err != nil {
  629. panic(err)
  630. }
  631. }
  632. // HTML renders the HTTP template specified by its file name.
  633. // It also updates the HTTP code and sets the Content-Type as "text/html".
  634. // See http://golang.org/doc/articles/wiki/
  635. func (c *Context) HTML(code int, name string, obj interface{}) {
  636. instance := c.engine.HTMLRender.Instance(name, obj)
  637. c.Render(code, instance)
  638. }
  639. // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
  640. // It also sets the Content-Type as "application/json".
  641. // WARNING: we recommend to use this only for development purposes since printing pretty JSON is
  642. // more CPU and bandwidth consuming. Use Context.JSON() instead.
  643. func (c *Context) IndentedJSON(code int, obj interface{}) {
  644. c.Render(code, render.IndentedJSON{Data: obj})
  645. }
  646. // SecureJSON serializes the given struct as Secure JSON into the response body.
  647. // Default prepends "while(1)," to response body if the given struct is array values.
  648. // It also sets the Content-Type as "application/json".
  649. func (c *Context) SecureJSON(code int, obj interface{}) {
  650. c.Render(code, render.SecureJSON{Prefix: c.engine.secureJsonPrefix, Data: obj})
  651. }
  652. // JSONP serializes the given struct as JSON into the response body.
  653. // It add padding to response body to request data from a server residing in a different domain than the client.
  654. // It also sets the Content-Type as "application/javascript".
  655. func (c *Context) JSONP(code int, obj interface{}) {
  656. callback := c.DefaultQuery("callback", "")
  657. if callback == "" {
  658. c.Render(code, render.JSON{Data: obj})
  659. return
  660. }
  661. c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
  662. }
  663. // JSON serializes the given struct as JSON into the response body.
  664. // It also sets the Content-Type as "application/json".
  665. func (c *Context) JSON(code int, obj interface{}) {
  666. c.Render(code, render.JSON{Data: obj})
  667. }
  668. // AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.
  669. // It also sets the Content-Type as "application/json".
  670. func (c *Context) AsciiJSON(code int, obj interface{}) {
  671. c.Render(code, render.AsciiJSON{Data: obj})
  672. }
  673. // XML serializes the given struct as XML into the response body.
  674. // It also sets the Content-Type as "application/xml".
  675. func (c *Context) XML(code int, obj interface{}) {
  676. c.Render(code, render.XML{Data: obj})
  677. }
  678. // YAML serializes the given struct as YAML into the response body.
  679. func (c *Context) YAML(code int, obj interface{}) {
  680. c.Render(code, render.YAML{Data: obj})
  681. }
  682. // ProtoBuf serializes the given struct as ProtoBuf into the response body.
  683. func (c *Context) ProtoBuf(code int, obj interface{}) {
  684. c.Render(code, render.ProtoBuf{Data: obj})
  685. }
  686. // String writes the given string into the response body.
  687. func (c *Context) String(code int, format string, values ...interface{}) {
  688. c.Render(code, render.String{Format: format, Data: values})
  689. }
  690. // Redirect returns a HTTP redirect to the specific location.
  691. func (c *Context) Redirect(code int, location string) {
  692. c.Render(-1, render.Redirect{
  693. Code: code,
  694. Location: location,
  695. Request: c.Request,
  696. })
  697. }
  698. // Data writes some data into the body stream and updates the HTTP code.
  699. func (c *Context) Data(code int, contentType string, data []byte) {
  700. c.Render(code, render.Data{
  701. ContentType: contentType,
  702. Data: data,
  703. })
  704. }
  705. // DataFromReader writes the specified reader into the body stream and updates the HTTP code.
  706. func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {
  707. c.Render(code, render.Reader{
  708. Headers: extraHeaders,
  709. ContentType: contentType,
  710. ContentLength: contentLength,
  711. Reader: reader,
  712. })
  713. }
  714. // File writes the specified file into the body stream in a efficient way.
  715. func (c *Context) File(filepath string) {
  716. http.ServeFile(c.Writer, c.Request, filepath)
  717. }
  718. // SSEvent writes a Server-Sent Event into the body stream.
  719. func (c *Context) SSEvent(name string, message interface{}) {
  720. c.Render(-1, sse.Event{
  721. Event: name,
  722. Data: message,
  723. })
  724. }
  725. // Stream sends a streaming response.
  726. func (c *Context) Stream(step func(w io.Writer) bool) {
  727. w := c.Writer
  728. clientGone := w.CloseNotify()
  729. for {
  730. select {
  731. case <-clientGone:
  732. return
  733. default:
  734. keepOpen := step(w)
  735. w.Flush()
  736. if !keepOpen {
  737. return
  738. }
  739. }
  740. }
  741. }
  742. /************************************/
  743. /******** CONTENT NEGOTIATION *******/
  744. /************************************/
  745. // Negotiate contains all negotiations data.
  746. type Negotiate struct {
  747. Offered []string
  748. HTMLName string
  749. HTMLData interface{}
  750. JSONData interface{}
  751. XMLData interface{}
  752. Data interface{}
  753. }
  754. // Negotiate calls different Render according acceptable Accept format.
  755. func (c *Context) Negotiate(code int, config Negotiate) {
  756. switch c.NegotiateFormat(config.Offered...) {
  757. case binding.MIMEJSON:
  758. data := chooseData(config.JSONData, config.Data)
  759. c.JSON(code, data)
  760. case binding.MIMEHTML:
  761. data := chooseData(config.HTMLData, config.Data)
  762. c.HTML(code, config.HTMLName, data)
  763. case binding.MIMEXML:
  764. data := chooseData(config.XMLData, config.Data)
  765. c.XML(code, data)
  766. default:
  767. c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  768. }
  769. }
  770. // NegotiateFormat returns an acceptable Accept format.
  771. func (c *Context) NegotiateFormat(offered ...string) string {
  772. assert1(len(offered) > 0, "you must provide at least one offer")
  773. if c.Accepted == nil {
  774. c.Accepted = parseAccept(c.requestHeader("Accept"))
  775. }
  776. if len(c.Accepted) == 0 {
  777. return offered[0]
  778. }
  779. for _, accepted := range c.Accepted {
  780. for _, offert := range offered {
  781. if accepted == offert {
  782. return offert
  783. }
  784. }
  785. }
  786. return ""
  787. }
  788. // SetAccepted sets Accept header data.
  789. func (c *Context) SetAccepted(formats ...string) {
  790. c.Accepted = formats
  791. }
  792. /************************************/
  793. /***** GOLANG.ORG/X/NET/CONTEXT *****/
  794. /************************************/
  795. // Deadline returns the time when work done on behalf of this context
  796. // should be canceled. Deadline returns ok==false when no deadline is
  797. // set. Successive calls to Deadline return the same results.
  798. func (c *Context) Deadline() (deadline time.Time, ok bool) {
  799. return
  800. }
  801. // Done returns a channel that's closed when work done on behalf of this
  802. // context should be canceled. Done may return nil if this context can
  803. // never be canceled. Successive calls to Done return the same value.
  804. func (c *Context) Done() <-chan struct{} {
  805. return nil
  806. }
  807. // Err returns a non-nil error value after Done is closed,
  808. // successive calls to Err return the same error.
  809. // If Done is not yet closed, Err returns nil.
  810. // If Done is closed, Err returns a non-nil error explaining why:
  811. // Canceled if the context was canceled
  812. // or DeadlineExceeded if the context's deadline passed.
  813. func (c *Context) Err() error {
  814. return nil
  815. }
  816. // Value returns the value associated with this context for key, or nil
  817. // if no value is associated with key. Successive calls to Value with
  818. // the same key returns the same result.
  819. func (c *Context) Value(key interface{}) interface{} {
  820. if key == 0 {
  821. return c.Request
  822. }
  823. if keyAsString, ok := key.(string); ok {
  824. val, _ := c.Get(keyAsString)
  825. return val
  826. }
  827. return nil
  828. }