context.go 13 KB

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