context.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. "math"
  9. "mime/multipart"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "time"
  15. "github.com/gin-gonic/gin/binding"
  16. "github.com/gin-gonic/gin/render"
  17. "gopkg.in/gin-contrib/sse.v0"
  18. )
  19. // Content-Type MIME of the most common data formats
  20. const (
  21. MIMEJSON = binding.MIMEJSON
  22. MIMEHTML = binding.MIMEHTML
  23. MIMEXML = binding.MIMEXML
  24. MIMEXML2 = binding.MIMEXML2
  25. MIMEPlain = binding.MIMEPlain
  26. MIMEPOSTForm = binding.MIMEPOSTForm
  27. MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
  28. )
  29. const (
  30. defaultMemory = 32 << 20 // 32 MB
  31. abortIndex int8 = math.MaxInt8 / 2
  32. )
  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 map[string]interface{}
  44. Errors errorMsgs
  45. Accepted []string
  46. }
  47. /************************************/
  48. /********** CONTEXT CREATION ********/
  49. /************************************/
  50. func (c *Context) reset() {
  51. c.Writer = &c.writermem
  52. c.Params = c.Params[0:0]
  53. c.handlers = nil
  54. c.index = -1
  55. c.Keys = nil
  56. c.Errors = c.Errors[0:0]
  57. c.Accepted = nil
  58. }
  59. // Copy returns a copy of the current context that can be safely used outside the request's scope.
  60. // This has to be used when the context has to be passed to a goroutine.
  61. func (c *Context) Copy() *Context {
  62. var cp = *c
  63. cp.writermem.ResponseWriter = nil
  64. cp.Writer = &cp.writermem
  65. cp.index = abortIndex
  66. cp.handlers = nil
  67. return &cp
  68. }
  69. // HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", this
  70. // function will return "main.handleGetUsers"
  71. func (c *Context) HandlerName() string {
  72. return nameOfFunction(c.handlers.Last())
  73. }
  74. /************************************/
  75. /*********** FLOW CONTROL ***********/
  76. /************************************/
  77. // Next should be used only inside middleware.
  78. // It executes the pending handlers in the chain inside the calling handler.
  79. // See example in github.
  80. func (c *Context) Next() {
  81. c.index++
  82. s := int8(len(c.handlers))
  83. for ; c.index < s; c.index++ {
  84. c.handlers[c.index](c)
  85. }
  86. }
  87. // IsAborted returns true if the current context was aborted.
  88. func (c *Context) IsAborted() bool {
  89. return c.index >= abortIndex
  90. }
  91. // Abort prevents pending handlers from being called. Note that this will not stop the current handler.
  92. // Let's say you have an authorization middleware that validates that the current request is authorized. If the
  93. // authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
  94. // for this request are not called.
  95. func (c *Context) Abort() {
  96. c.index = abortIndex
  97. }
  98. // AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
  99. // For example, a failed attempt to authentificate a request could use: context.AbortWithStatus(401).
  100. func (c *Context) AbortWithStatus(code int) {
  101. c.Status(code)
  102. c.Writer.WriteHeaderNow()
  103. c.Abort()
  104. }
  105. // AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body
  106. // It also sets the Content-Type as "application/json".
  107. func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) {
  108. c.Abort()
  109. c.JSON(code, jsonObj)
  110. }
  111. // AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and
  112. // pushes the specified error to `c.Errors`.
  113. // See Context.Error() for more details.
  114. func (c *Context) AbortWithError(code int, err error) *Error {
  115. c.AbortWithStatus(code)
  116. return c.Error(err)
  117. }
  118. /************************************/
  119. /********* ERROR MANAGEMENT *********/
  120. /************************************/
  121. // Attaches an error to the current context. The error is pushed to a list of errors.
  122. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  123. // A middleware can be used to collect all the errors
  124. // and push them to a database together, print a log, or append it in the HTTP response.
  125. func (c *Context) Error(err error) *Error {
  126. var parsedError *Error
  127. switch err.(type) {
  128. case *Error:
  129. parsedError = err.(*Error)
  130. default:
  131. parsedError = &Error{
  132. Err: err,
  133. Type: ErrorTypePrivate,
  134. }
  135. }
  136. c.Errors = append(c.Errors, parsedError)
  137. return parsedError
  138. }
  139. /************************************/
  140. /******** METADATA MANAGEMENT********/
  141. /************************************/
  142. // Set is used to store a new key/value pair exclusivelly for this context.
  143. // It also lazy initializes c.Keys if it was not used previously.
  144. func (c *Context) Set(key string, value interface{}) {
  145. if c.Keys == nil {
  146. c.Keys = make(map[string]interface{})
  147. }
  148. c.Keys[key] = value
  149. }
  150. // Get returns the value for the given key, ie: (value, true).
  151. // If the value does not exists it returns (nil, false)
  152. func (c *Context) Get(key string) (value interface{}, exists bool) {
  153. value, exists = c.Keys[key]
  154. return
  155. }
  156. // MustGet returns the value for the given key if it exists, otherwise it panics.
  157. func (c *Context) MustGet(key string) interface{} {
  158. if value, exists := c.Get(key); exists {
  159. return value
  160. }
  161. panic("Key \"" + key + "\" does not exist")
  162. }
  163. /************************************/
  164. /************ INPUT DATA ************/
  165. /************************************/
  166. // Param returns the value of the URL param.
  167. // It is a shortcut for c.Params.ByName(key)
  168. // router.GET("/user/:id", func(c *gin.Context) {
  169. // // a GET request to /user/john
  170. // id := c.Param("id") // id == "john"
  171. // })
  172. func (c *Context) Param(key string) string {
  173. return c.Params.ByName(key)
  174. }
  175. // Query returns the keyed url query value if it exists,
  176. // othewise it returns an empty string `("")`.
  177. // It is shortcut for `c.Request.URL.Query().Get(key)`
  178. // GET /path?id=1234&name=Manu&value=
  179. // c.Query("id") == "1234"
  180. // c.Query("name") == "Manu"
  181. // c.Query("value") == ""
  182. // c.Query("wtf") == ""
  183. func (c *Context) Query(key string) string {
  184. value, _ := c.GetQuery(key)
  185. return value
  186. }
  187. // DefaultQuery returns the keyed url query value if it exists,
  188. // othewise it returns the specified defaultValue string.
  189. // See: Query() and GetQuery() for further information.
  190. // GET /?name=Manu&lastname=
  191. // c.DefaultQuery("name", "unknown") == "Manu"
  192. // c.DefaultQuery("id", "none") == "none"
  193. // c.DefaultQuery("lastname", "none") == ""
  194. func (c *Context) DefaultQuery(key, defaultValue string) string {
  195. if value, ok := c.GetQuery(key); ok {
  196. return value
  197. }
  198. return defaultValue
  199. }
  200. // GetQuery is like Query(), it returns the keyed url query value
  201. // if it exists `(value, true)` (even when the value is an empty string),
  202. // othewise it returns `("", false)`.
  203. // It is shortcut for `c.Request.URL.Query().Get(key)`
  204. // GET /?name=Manu&lastname=
  205. // ("Manu", true) == c.GetQuery("name")
  206. // ("", false) == c.GetQuery("id")
  207. // ("", true) == c.GetQuery("lastname")
  208. func (c *Context) GetQuery(key string) (string, bool) {
  209. if values, ok := c.GetQueryArray(key); ok {
  210. return values[0], ok
  211. }
  212. return "", false
  213. }
  214. // QueryArray returns a slice of strings for a given query key.
  215. // The length of the slice depends on the number of params with the given key.
  216. func (c *Context) QueryArray(key string) []string {
  217. values, _ := c.GetQueryArray(key)
  218. return values
  219. }
  220. // GetQueryArray returns a slice of strings for a given query key, plus
  221. // a boolean value whether at least one value exists for the given key.
  222. func (c *Context) GetQueryArray(key string) ([]string, bool) {
  223. req := c.Request
  224. if values, ok := req.URL.Query()[key]; ok && len(values) > 0 {
  225. return values, true
  226. }
  227. return []string{}, false
  228. }
  229. // PostForm returns the specified key from a POST urlencoded form or multipart form
  230. // when it exists, otherwise it returns an empty string `("")`.
  231. func (c *Context) PostForm(key string) string {
  232. value, _ := c.GetPostForm(key)
  233. return value
  234. }
  235. // DefaultPostForm returns the specified key from a POST urlencoded form or multipart form
  236. // when it exists, otherwise it returns the specified defaultValue string.
  237. // See: PostForm() and GetPostForm() for further information.
  238. func (c *Context) DefaultPostForm(key, defaultValue string) string {
  239. if value, ok := c.GetPostForm(key); ok {
  240. return value
  241. }
  242. return defaultValue
  243. }
  244. // GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded
  245. // form or multipart form when it exists `(value, true)` (even when the value is an empty string),
  246. // otherwise it returns ("", false).
  247. // For example, during a PATCH request to update the user's email:
  248. // email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
  249. // email= --> ("", true) := GetPostForm("email") // set email to ""
  250. // --> ("", false) := GetPostForm("email") // do nothing with email
  251. func (c *Context) GetPostForm(key string) (string, bool) {
  252. if values, ok := c.GetPostFormArray(key); ok {
  253. return values[0], ok
  254. }
  255. return "", false
  256. }
  257. // PostFormArray returns a slice of strings for a given form key.
  258. // The length of the slice depends on the number of params with the given key.
  259. func (c *Context) PostFormArray(key string) []string {
  260. values, _ := c.GetPostFormArray(key)
  261. return values
  262. }
  263. // GetPostFormArray returns a slice of strings for a given form key, plus
  264. // a boolean value whether at least one value exists for the given key.
  265. func (c *Context) GetPostFormArray(key string) ([]string, bool) {
  266. req := c.Request
  267. req.ParseForm()
  268. req.ParseMultipartForm(defaultMemory)
  269. if values := req.PostForm[key]; len(values) > 0 {
  270. return values, true
  271. }
  272. if req.MultipartForm != nil && req.MultipartForm.File != nil {
  273. if values := req.MultipartForm.Value[key]; len(values) > 0 {
  274. return values, true
  275. }
  276. }
  277. return []string{}, false
  278. }
  279. // FormFile returns the first file for the provided form key.
  280. func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
  281. _, fh, err := c.Request.FormFile(name)
  282. return fh, err
  283. }
  284. // MultipartForm is the parsed multipart form, including file uploads.
  285. func (c *Context) MultipartForm() (*multipart.Form, error) {
  286. err := c.Request.ParseMultipartForm(defaultMemory)
  287. return c.Request.MultipartForm, err
  288. }
  289. // Bind checks the Content-Type to select a binding engine automatically,
  290. // Depending the "Content-Type" header different bindings are used:
  291. // "application/json" --> JSON binding
  292. // "application/xml" --> XML binding
  293. // otherwise --> returns an error
  294. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
  295. // It decodes the json payload into the struct specified as a pointer.
  296. // Like ParseBody() but this method also writes a 400 error if the json is not valid.
  297. func (c *Context) Bind(obj interface{}) error {
  298. b := binding.Default(c.Request.Method, c.ContentType())
  299. return c.BindWith(obj, b)
  300. }
  301. // BindJSON is a shortcut for c.BindWith(obj, binding.JSON)
  302. func (c *Context) BindJSON(obj interface{}) error {
  303. return c.BindWith(obj, binding.JSON)
  304. }
  305. // BindWith binds the passed struct pointer using the specified binding engine.
  306. // See the binding package.
  307. func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
  308. if err := b.Bind(c.Request, obj); err != nil {
  309. c.AbortWithError(400, err).SetType(ErrorTypeBind)
  310. return err
  311. }
  312. return nil
  313. }
  314. // ClientIP implements a best effort algorithm to return the real client IP, it parses
  315. // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
  316. // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
  317. func (c *Context) ClientIP() string {
  318. if c.engine.ForwardedByClientIP {
  319. clientIP := c.requestHeader("X-Forwarded-For")
  320. if index := strings.IndexByte(clientIP, ','); index >= 0 {
  321. clientIP = clientIP[0:index]
  322. }
  323. clientIP = strings.TrimSpace(clientIP)
  324. if len(clientIP) > 0 {
  325. return clientIP
  326. }
  327. clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
  328. if len(clientIP) > 0 {
  329. return clientIP
  330. }
  331. }
  332. if c.engine.AppEngine {
  333. if addr := c.Request.Header.Get("X-Appengine-Remote-Addr"); addr != "" {
  334. return addr
  335. }
  336. }
  337. if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
  338. return ip
  339. }
  340. return ""
  341. }
  342. // ContentType returns the Content-Type header of the request.
  343. func (c *Context) ContentType() string {
  344. return filterFlags(c.requestHeader("Content-Type"))
  345. }
  346. // IsWebsocket returns true if the request headers indicate that a websocket
  347. // handshake is being initiated by the client.
  348. func (c *Context) IsWebsocket() bool {
  349. if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
  350. strings.ToLower(c.requestHeader("Upgrade")) == "websocket" {
  351. return true
  352. }
  353. return false
  354. }
  355. func (c *Context) requestHeader(key string) string {
  356. if values, _ := c.Request.Header[key]; len(values) > 0 {
  357. return values[0]
  358. }
  359. return ""
  360. }
  361. /************************************/
  362. /******** RESPONSE RENDERING ********/
  363. /************************************/
  364. // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function
  365. func bodyAllowedForStatus(status int) bool {
  366. switch {
  367. case status >= 100 && status <= 199:
  368. return false
  369. case status == 204:
  370. return false
  371. case status == 304:
  372. return false
  373. }
  374. return true
  375. }
  376. func (c *Context) Status(code int) {
  377. c.writermem.WriteHeader(code)
  378. }
  379. // Header is a intelligent shortcut for c.Writer.Header().Set(key, value)
  380. // It writes a header in the response.
  381. // If value == "", this method removes the header `c.Writer.Header().Del(key)`
  382. func (c *Context) Header(key, value string) {
  383. if len(value) == 0 {
  384. c.Writer.Header().Del(key)
  385. } else {
  386. c.Writer.Header().Set(key, value)
  387. }
  388. }
  389. func (c *Context) SetCookie(
  390. name string,
  391. value string,
  392. maxAge int,
  393. path string,
  394. domain string,
  395. secure bool,
  396. httpOnly bool,
  397. ) {
  398. if path == "" {
  399. path = "/"
  400. }
  401. http.SetCookie(c.Writer, &http.Cookie{
  402. Name: name,
  403. Value: url.QueryEscape(value),
  404. MaxAge: maxAge,
  405. Path: path,
  406. Domain: domain,
  407. Secure: secure,
  408. HttpOnly: httpOnly,
  409. })
  410. }
  411. func (c *Context) Cookie(name string) (string, error) {
  412. cookie, err := c.Request.Cookie(name)
  413. if err != nil {
  414. return "", err
  415. }
  416. val, _ := url.QueryUnescape(cookie.Value)
  417. return val, nil
  418. }
  419. func (c *Context) Render(code int, r render.Render) {
  420. c.Status(code)
  421. if !bodyAllowedForStatus(code) {
  422. r.WriteContentType(c.Writer)
  423. c.Writer.WriteHeaderNow()
  424. return
  425. }
  426. if err := r.Render(c.Writer); err != nil {
  427. panic(err)
  428. }
  429. }
  430. // HTML renders the HTTP template specified by its file name.
  431. // It also updates the HTTP code and sets the Content-Type as "text/html".
  432. // See http://golang.org/doc/articles/wiki/
  433. func (c *Context) HTML(code int, name string, obj interface{}) {
  434. instance := c.engine.HTMLRender.Instance(name, obj)
  435. c.Render(code, instance)
  436. }
  437. // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
  438. // It also sets the Content-Type as "application/json".
  439. // WARNING: we recommend to use this only for development propuses since printing pretty JSON is
  440. // more CPU and bandwidth consuming. Use Context.JSON() instead.
  441. func (c *Context) IndentedJSON(code int, obj interface{}) {
  442. c.Render(code, render.IndentedJSON{Data: obj})
  443. }
  444. // JSON serializes the given struct as JSON into the response body.
  445. // It also sets the Content-Type as "application/json".
  446. func (c *Context) JSON(code int, obj interface{}) {
  447. c.Render(code, render.JSON{Data: obj})
  448. }
  449. // XML serializes the given struct as XML into the response body.
  450. // It also sets the Content-Type as "application/xml".
  451. func (c *Context) XML(code int, obj interface{}) {
  452. c.Render(code, render.XML{Data: obj})
  453. }
  454. // YAML serializes the given struct as YAML into the response body.
  455. func (c *Context) YAML(code int, obj interface{}) {
  456. c.Render(code, render.YAML{Data: obj})
  457. }
  458. // String writes the given string into the response body.
  459. func (c *Context) String(code int, format string, values ...interface{}) {
  460. c.Render(code, render.String{Format: format, Data: values})
  461. }
  462. // Redirect returns a HTTP redirect to the specific location.
  463. func (c *Context) Redirect(code int, location string) {
  464. c.Render(-1, render.Redirect{
  465. Code: code,
  466. Location: location,
  467. Request: c.Request,
  468. })
  469. }
  470. // Data writes some data into the body stream and updates the HTTP code.
  471. func (c *Context) Data(code int, contentType string, data []byte) {
  472. c.Render(code, render.Data{
  473. ContentType: contentType,
  474. Data: data,
  475. })
  476. }
  477. // File writes the specified file into the body stream in a efficient way.
  478. func (c *Context) File(filepath string) {
  479. http.ServeFile(c.Writer, c.Request, filepath)
  480. }
  481. // SSEvent writes a Server-Sent Event into the body stream.
  482. func (c *Context) SSEvent(name string, message interface{}) {
  483. c.Render(-1, sse.Event{
  484. Event: name,
  485. Data: message,
  486. })
  487. }
  488. func (c *Context) Stream(step func(w io.Writer) bool) {
  489. w := c.Writer
  490. clientGone := w.CloseNotify()
  491. for {
  492. select {
  493. case <-clientGone:
  494. return
  495. default:
  496. keepOpen := step(w)
  497. w.Flush()
  498. if !keepOpen {
  499. return
  500. }
  501. }
  502. }
  503. }
  504. /************************************/
  505. /******** CONTENT NEGOTIATION *******/
  506. /************************************/
  507. type Negotiate struct {
  508. Offered []string
  509. HTMLName string
  510. HTMLData interface{}
  511. JSONData interface{}
  512. XMLData interface{}
  513. Data interface{}
  514. }
  515. func (c *Context) Negotiate(code int, config Negotiate) {
  516. switch c.NegotiateFormat(config.Offered...) {
  517. case binding.MIMEJSON:
  518. data := chooseData(config.JSONData, config.Data)
  519. c.JSON(code, data)
  520. case binding.MIMEHTML:
  521. data := chooseData(config.HTMLData, config.Data)
  522. c.HTML(code, config.HTMLName, data)
  523. case binding.MIMEXML:
  524. data := chooseData(config.XMLData, config.Data)
  525. c.XML(code, data)
  526. default:
  527. c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  528. }
  529. }
  530. func (c *Context) NegotiateFormat(offered ...string) string {
  531. assert1(len(offered) > 0, "you must provide at least one offer")
  532. if c.Accepted == nil {
  533. c.Accepted = parseAccept(c.requestHeader("Accept"))
  534. }
  535. if len(c.Accepted) == 0 {
  536. return offered[0]
  537. }
  538. for _, accepted := range c.Accepted {
  539. for _, offert := range offered {
  540. if accepted == offert {
  541. return offert
  542. }
  543. }
  544. }
  545. return ""
  546. }
  547. func (c *Context) SetAccepted(formats ...string) {
  548. c.Accepted = formats
  549. }
  550. /************************************/
  551. /***** GOLANG.ORG/X/NET/CONTEXT *****/
  552. /************************************/
  553. func (c *Context) Deadline() (deadline time.Time, ok bool) {
  554. return
  555. }
  556. func (c *Context) Done() <-chan struct{} {
  557. return nil
  558. }
  559. func (c *Context) Err() error {
  560. return nil
  561. }
  562. func (c *Context) Value(key interface{}) interface{} {
  563. if key == 0 {
  564. return c.Request
  565. }
  566. if keyAsString, ok := key.(string); ok {
  567. val, _ := c.Get(keyAsString)
  568. return val
  569. }
  570. return nil
  571. }