context.go 17 KB

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