context.go 19 KB

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