context.go 13 KB

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