http urls monitor.

context.go 29KB

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