context.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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/http"
  10. "strings"
  11. "time"
  12. "github.com/gin-gonic/gin/binding"
  13. "github.com/gin-gonic/gin/render"
  14. "github.com/manucorporat/sse"
  15. "golang.org/x/net/context"
  16. )
  17. // Content-Type MIME of the most common data formats
  18. const (
  19. MIMEJSON = binding.MIMEJSON
  20. MIMEHTML = binding.MIMEHTML
  21. MIMEXML = binding.MIMEXML
  22. MIMEXML2 = binding.MIMEXML2
  23. MIMEPlain = binding.MIMEPlain
  24. MIMEPOSTForm = binding.MIMEPOSTForm
  25. MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
  26. )
  27. const abortIndex int8 = math.MaxInt8 / 2
  28. // Context is the most important part of gin. It allows us to pass variables between middleware,
  29. // manage the flow, validate the JSON of a request and render a JSON response for example.
  30. type Context struct {
  31. writermem responseWriter
  32. Request *http.Request
  33. Writer ResponseWriter
  34. Params Params
  35. handlers HandlersChain
  36. index int8
  37. engine *Engine
  38. Keys map[string]interface{}
  39. Errors errorMsgs
  40. Accepted []string
  41. }
  42. var _ context.Context = &Context{}
  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 Context = *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 handle'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 in the middlewares.
  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 currect context was aborted.
  84. func (c *Context) IsAborted() bool {
  85. return c.index >= abortIndex
  86. }
  87. // Abort stops the system to continue calling the pending handlers in the chain.
  88. // Let's say you have an authorization middleware that validates if the request is authorized
  89. // if the authorization fails (the password does not match). This method (Abort()) should be called
  90. // in order to stop the execution of the actual handler.
  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.Writer.WriteHeader(code)
  98. c.Abort()
  99. }
  100. // AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and
  101. // pushes the specified error to `c.Errors`.
  102. // See Context.Error() for more details.
  103. func (c *Context) AbortWithError(code int, err error) *Error {
  104. c.AbortWithStatus(code)
  105. return c.Error(err)
  106. }
  107. /************************************/
  108. /********* ERROR MANAGEMENT *********/
  109. /************************************/
  110. // Attaches an error to the current context. The error is pushed to a list of errors.
  111. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  112. // A middleware can be used to collect all the errors
  113. // and push them to a database together, print a log, or append it in the HTTP response.
  114. func (c *Context) Error(err error) *Error {
  115. var parsedError *Error
  116. switch err.(type) {
  117. case *Error:
  118. parsedError = err.(*Error)
  119. default:
  120. parsedError = &Error{
  121. Err: err,
  122. Type: ErrorTypePrivate,
  123. }
  124. }
  125. c.Errors = append(c.Errors, parsedError)
  126. return parsedError
  127. }
  128. /************************************/
  129. /******** METADATA MANAGEMENT********/
  130. /************************************/
  131. // Set is used to store a new key/value pair exclusivelly for this context.
  132. // It also lazy initializes c.Keys if it was not used previously.
  133. func (c *Context) Set(key string, value interface{}) {
  134. if c.Keys == nil {
  135. c.Keys = make(map[string]interface{})
  136. }
  137. c.Keys[key] = value
  138. }
  139. // Get returns the value for the given key, ie: (value, true).
  140. // If the value does not exists it returns (nil, false)
  141. func (c *Context) Get(key string) (value interface{}, exists bool) {
  142. if c.Keys != nil {
  143. value, exists = c.Keys[key]
  144. }
  145. return
  146. }
  147. // Returns the value for the given key if it exists, otherwise it panics.
  148. func (c *Context) MustGet(key string) interface{} {
  149. if value, exists := c.Get(key); exists {
  150. return value
  151. }
  152. panic("Key \"" + key + "\" does not exist")
  153. }
  154. /************************************/
  155. /************ INPUT DATA ************/
  156. /************************************/
  157. // Query is a shortcut for c.Request.URL.Query().Get(key)
  158. func (c *Context) Query(key string) (va string) {
  159. va, _ = c.query(key)
  160. return
  161. }
  162. // PostForm is a shortcut for c.Request.PostFormValue(key)
  163. func (c *Context) PostForm(key string) (va string) {
  164. va, _ = c.postForm(key)
  165. return
  166. }
  167. // Param is a shortcut for c.Params.ByName(key)
  168. func (c *Context) Param(key string) string {
  169. return c.Params.ByName(key)
  170. }
  171. func (c *Context) DefaultPostForm(key, defaultValue string) string {
  172. if va, ok := c.postForm(key); ok {
  173. return va
  174. }
  175. return defaultValue
  176. }
  177. // DefaultQuery returns the keyed url query value if it exists, othewise it returns the
  178. // specified defaultValue.
  179. // ```
  180. // /?name=Manu
  181. // c.DefaultQuery("name", "unknown") == "Manu"
  182. // c.DefaultQuery("id", "none") == "none"
  183. // ```
  184. func (c *Context) DefaultQuery(key, defaultValue string) string {
  185. if va, ok := c.query(key); ok {
  186. return va
  187. }
  188. return defaultValue
  189. }
  190. func (c *Context) query(key string) (string, bool) {
  191. req := c.Request
  192. if values, ok := req.URL.Query()[key]; ok && len(values) > 0 {
  193. return values[0], true
  194. }
  195. return "", false
  196. }
  197. func (c *Context) postForm(key string) (string, bool) {
  198. req := c.Request
  199. req.ParseMultipartForm(32 << 20) // 32 MB
  200. if values := req.PostForm[key]; len(values) > 0 {
  201. return values[0], true
  202. }
  203. if req.MultipartForm != nil && req.MultipartForm.File != nil {
  204. if values := req.MultipartForm.Value[key]; len(values) > 0 {
  205. return values[0], true
  206. }
  207. }
  208. return "", false
  209. }
  210. // Bind checks the Content-Type to select a binding engine automatically,
  211. // Depending the "Content-Type" header different bindings are used:
  212. // "application/json" --> JSON binding
  213. // "application/xml" --> XML binding
  214. // otherwise --> returns an error
  215. // If Parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
  216. // It decodes the json payload into the struct specified as a pointer.
  217. // Like ParseBody() but this method also writes a 400 error if the json is not valid.
  218. func (c *Context) Bind(obj interface{}) error {
  219. b := binding.Default(c.Request.Method, c.ContentType())
  220. return c.BindWith(obj, b)
  221. }
  222. // BindJSON is a shortcut for c.BindWith(obj, binding.JSON)
  223. func (c *Context) BindJSON(obj interface{}) error {
  224. return c.BindWith(obj, binding.JSON)
  225. }
  226. // BindWith binds the passed struct pointer using the specified binding engine.
  227. // See the binding package.
  228. func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
  229. if err := b.Bind(c.Request, obj); err != nil {
  230. c.AbortWithError(400, err).SetType(ErrorTypeBind)
  231. return err
  232. }
  233. return nil
  234. }
  235. // ClientIP implements a best effort algorithm to return the real client IP, it parses
  236. // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
  237. func (c *Context) ClientIP() string {
  238. if c.engine.ForwardedByClientIP {
  239. clientIP := strings.TrimSpace(c.requestHeader("X-Real-Ip"))
  240. if len(clientIP) > 0 {
  241. return clientIP
  242. }
  243. clientIP = c.requestHeader("X-Forwarded-For")
  244. if index := strings.IndexByte(clientIP, ','); index >= 0 {
  245. clientIP = clientIP[0:index]
  246. }
  247. clientIP = strings.TrimSpace(clientIP)
  248. if len(clientIP) > 0 {
  249. return clientIP
  250. }
  251. }
  252. return strings.TrimSpace(c.Request.RemoteAddr)
  253. }
  254. // ContentType returns the Content-Type header of the request.
  255. func (c *Context) ContentType() string {
  256. return filterFlags(c.requestHeader("Content-Type"))
  257. }
  258. func (c *Context) requestHeader(key string) string {
  259. if values, _ := c.Request.Header[key]; len(values) > 0 {
  260. return values[0]
  261. }
  262. return ""
  263. }
  264. /************************************/
  265. /******** RESPONSE RENDERING ********/
  266. /************************************/
  267. // Header is a intelligent shortcut for c.Writer.Header().Set(key, value)
  268. // It writes a header in the response.
  269. // If value == "", this method removes the header `c.Writer.Header().Del(key)`
  270. func (c *Context) Header(key, value string) {
  271. if len(value) == 0 {
  272. c.Writer.Header().Del(key)
  273. } else {
  274. c.Writer.Header().Set(key, value)
  275. }
  276. }
  277. func (c *Context) Render(code int, r render.Render) {
  278. c.writermem.WriteHeader(code)
  279. if err := r.Render(c.Writer); err != nil {
  280. c.renderError(err)
  281. }
  282. }
  283. func (c *Context) renderError(err error) {
  284. debugPrintError(err)
  285. c.AbortWithError(500, err).SetType(ErrorTypeRender)
  286. }
  287. // HTML renders the HTTP template specified by its file name.
  288. // It also updates the HTTP code and sets the Content-Type as "text/html".
  289. // See http://golang.org/doc/articles/wiki/
  290. func (c *Context) HTML(code int, name string, obj interface{}) {
  291. instance := c.engine.HTMLRender.Instance(name, obj)
  292. c.Render(code, instance)
  293. }
  294. // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
  295. // It also sets the Content-Type as "application/json".
  296. // WARNING: we recommend to use this only for development propuses since printing pretty JSON is
  297. // more CPU and bandwidth consuming. Use Context.JSON() instead.
  298. func (c *Context) IndentedJSON(code int, obj interface{}) {
  299. c.Render(code, render.IndentedJSON{Data: obj})
  300. }
  301. // JSON serializes the given struct as JSON into the response body.
  302. // It also sets the Content-Type as "application/json".
  303. func (c *Context) JSON(code int, obj interface{}) {
  304. c.writermem.WriteHeader(code)
  305. if err := render.WriteJSON(c.Writer, obj); err != nil {
  306. c.renderError(err)
  307. }
  308. }
  309. // XML serializes the given struct as XML into the response body.
  310. // It also sets the Content-Type as "application/xml".
  311. func (c *Context) XML(code int, obj interface{}) {
  312. c.Render(code, render.XML{Data: obj})
  313. }
  314. // String writes the given string into the response body.
  315. func (c *Context) String(code int, format string, values ...interface{}) {
  316. c.writermem.WriteHeader(code)
  317. render.WriteString(c.Writer, format, values)
  318. }
  319. // Redirect returns a HTTP redirect to the specific location.
  320. func (c *Context) Redirect(code int, location string) {
  321. c.Render(-1, render.Redirect{
  322. Code: code,
  323. Location: location,
  324. Request: c.Request,
  325. })
  326. }
  327. // Data writes some data into the body stream and updates the HTTP code.
  328. func (c *Context) Data(code int, contentType string, data []byte) {
  329. c.Render(code, render.Data{
  330. ContentType: contentType,
  331. Data: data,
  332. })
  333. }
  334. // File writes the specified file into the body stream in a efficient way.
  335. func (c *Context) File(filepath string) {
  336. http.ServeFile(c.Writer, c.Request, filepath)
  337. }
  338. // SSEvent writes a Server-Sent Event into the body stream.
  339. func (c *Context) SSEvent(name string, message interface{}) {
  340. c.Render(-1, sse.Event{
  341. Event: name,
  342. Data: message,
  343. })
  344. }
  345. func (c *Context) Stream(step func(w io.Writer) bool) {
  346. w := c.Writer
  347. clientGone := w.CloseNotify()
  348. for {
  349. select {
  350. case <-clientGone:
  351. return
  352. default:
  353. keepopen := step(w)
  354. w.Flush()
  355. if !keepopen {
  356. return
  357. }
  358. }
  359. }
  360. }
  361. /************************************/
  362. /******** CONTENT NEGOTIATION *******/
  363. /************************************/
  364. type Negotiate struct {
  365. Offered []string
  366. HTMLName string
  367. HTMLData interface{}
  368. JSONData interface{}
  369. XMLData interface{}
  370. Data interface{}
  371. }
  372. func (c *Context) Negotiate(code int, config Negotiate) {
  373. switch c.NegotiateFormat(config.Offered...) {
  374. case binding.MIMEJSON:
  375. data := chooseData(config.JSONData, config.Data)
  376. c.JSON(code, data)
  377. case binding.MIMEHTML:
  378. data := chooseData(config.HTMLData, config.Data)
  379. c.HTML(code, config.HTMLName, data)
  380. case binding.MIMEXML:
  381. data := chooseData(config.XMLData, config.Data)
  382. c.XML(code, data)
  383. default:
  384. c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  385. }
  386. }
  387. func (c *Context) NegotiateFormat(offered ...string) string {
  388. if len(offered) == 0 {
  389. panic("you must provide at least one offer")
  390. }
  391. if c.Accepted == nil {
  392. c.Accepted = parseAccept(c.requestHeader("Accept"))
  393. }
  394. if len(c.Accepted) == 0 {
  395. return offered[0]
  396. }
  397. for _, accepted := range c.Accepted {
  398. for _, offert := range offered {
  399. if accepted == offert {
  400. return offert
  401. }
  402. }
  403. }
  404. return ""
  405. }
  406. func (c *Context) SetAccepted(formats ...string) {
  407. c.Accepted = formats
  408. }
  409. /************************************/
  410. /***** GOLANG.ORG/X/NET/CONTEXT *****/
  411. /************************************/
  412. func (c *Context) Deadline() (deadline time.Time, ok bool) {
  413. return
  414. }
  415. func (c *Context) Done() <-chan struct{} {
  416. return nil
  417. }
  418. func (c *Context) Err() error {
  419. return nil
  420. }
  421. func (c *Context) Value(key interface{}) interface{} {
  422. if key == 0 {
  423. return c.Request
  424. }
  425. if keyAsString, ok := key.(string); ok {
  426. val, _ := c.Get(keyAsString)
  427. return val
  428. }
  429. return nil
  430. }