context.go 16 KB

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