context.go 13 KB

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