context.go 13 KB

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