context.go 17 KB

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