context.go 14 KB

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