context.go 18 KB

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