context.go 17 KB

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