context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 = math.MaxInt8 / 2
  27. // Param is a single URL parameter, consisting of a key and a value.
  28. type Param struct {
  29. Key string
  30. Value string
  31. }
  32. // Params is a Param-slice, as returned by the router.
  33. // The slice is ordered, the first URL parameter is also the first slice value.
  34. // It is therefore safe to read values by the index.
  35. type Params []Param
  36. // ByName returns the value of the first Param which key matches the given name.
  37. // If no matching Param is found, an empty string is returned.
  38. func (ps Params) Get(name string) (string, bool) {
  39. for _, entry := range ps {
  40. if entry.Key == name {
  41. return entry.Value, true
  42. }
  43. }
  44. return "", false
  45. }
  46. func (ps Params) ByName(name string) (va string) {
  47. va, _ = ps.Get(name)
  48. return
  49. }
  50. // Context is the most important part of gin. It allows us to pass variables between middleware,
  51. // manage the flow, validate the JSON of a request and render a JSON response for example.
  52. type Context struct {
  53. writermem responseWriter
  54. Request *http.Request
  55. Writer ResponseWriter
  56. Params Params
  57. handlers HandlersChain
  58. index int8
  59. engine *Engine
  60. Keys map[string]interface{}
  61. Errors errorMsgs
  62. Accepted []string
  63. }
  64. var _ context.Context = &Context{}
  65. /************************************/
  66. /********** CONTEXT CREATION ********/
  67. /************************************/
  68. func (c *Context) reset() {
  69. c.Writer = &c.writermem
  70. c.Params = c.Params[0:0]
  71. c.handlers = nil
  72. c.index = -1
  73. c.Keys = nil
  74. c.Errors = c.Errors[0:0]
  75. c.Accepted = nil
  76. }
  77. func (c *Context) Copy() *Context {
  78. var cp Context = *c
  79. cp.writermem.ResponseWriter = nil
  80. cp.Writer = &cp.writermem
  81. cp.index = AbortIndex
  82. cp.handlers = nil
  83. return &cp
  84. }
  85. /************************************/
  86. /*************** FLOW ***************/
  87. /************************************/
  88. // Next should be used only in the middlewares.
  89. // It executes the pending handlers in the chain inside the calling handler.
  90. // See example in github.
  91. func (c *Context) Next() {
  92. c.index++
  93. s := int8(len(c.handlers))
  94. for ; c.index < s; c.index++ {
  95. c.handlers[c.index](c)
  96. }
  97. }
  98. // Forces the system to not continue calling the pending handlers in the chain.
  99. func (c *Context) Abort() {
  100. c.index = AbortIndex
  101. }
  102. // AbortWithStatus is the same as Abort but also writes the specified response status code.
  103. // For example, the first handler checks if the request is authorized. If it's not, context.AbortWithStatus(401) should be called.
  104. func (c *Context) AbortWithStatus(code int) {
  105. c.Writer.WriteHeader(code)
  106. c.Abort()
  107. }
  108. func (c *Context) AbortWithError(code int, err error) *Error {
  109. c.AbortWithStatus(code)
  110. return c.Error(err)
  111. }
  112. func (c *Context) IsAborted() bool {
  113. return c.index == AbortIndex
  114. }
  115. /************************************/
  116. /********* ERROR MANAGEMENT *********/
  117. /************************************/
  118. // Attaches an error to the current context. The error is pushed to a list of errors.
  119. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  120. // 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.
  121. func (c *Context) Error(err error) *Error {
  122. var parsedError *Error
  123. switch err.(type) {
  124. case *Error:
  125. parsedError = err.(*Error)
  126. default:
  127. parsedError = &Error{
  128. Err: err,
  129. Type: ErrorTypePrivate,
  130. }
  131. }
  132. c.Errors = append(c.Errors, parsedError)
  133. return parsedError
  134. }
  135. /************************************/
  136. /******** METADATA MANAGEMENT********/
  137. /************************************/
  138. // Sets a new pair key/value just for the specified context.
  139. // It also lazy initializes the hashmap.
  140. func (c *Context) Set(key string, value interface{}) {
  141. if c.Keys == nil {
  142. c.Keys = make(map[string]interface{})
  143. }
  144. c.Keys[key] = value
  145. }
  146. // Get returns the value for the given key or an error if the key does not exist.
  147. func (c *Context) Get(key string) (value interface{}, exists bool) {
  148. if c.Keys != nil {
  149. value, exists = c.Keys[key]
  150. }
  151. return
  152. }
  153. // MustGet returns the value for the given key or panics if the value doesn't exist.
  154. func (c *Context) MustGet(key string) interface{} {
  155. if value, exists := c.Get(key); exists {
  156. return value
  157. }
  158. panic("Key \"" + key + "\" does not exist")
  159. }
  160. /************************************/
  161. /************ INPUT DATA ************/
  162. /************************************/
  163. /** Shortcut for c.Request.URL.Query().Get(key) */
  164. func (c *Context) Query(key string) (va string) {
  165. va, _ = c.query(key)
  166. return
  167. }
  168. /** Shortcut for c.Request.PostFormValue(key) */
  169. func (c *Context) PostForm(key string) (va string) {
  170. va, _ = c.postForm(key)
  171. return
  172. }
  173. /** 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. func (c *Context) DefaultQuery(key, defaultValue string) string {
  184. if va, ok := c.query(key); ok {
  185. return va
  186. }
  187. return defaultValue
  188. }
  189. func (c *Context) query(key string) (string, bool) {
  190. req := c.Request
  191. if values, ok := req.URL.Query()[key]; ok && len(values) > 0 {
  192. return values[0], true
  193. }
  194. return "", false
  195. }
  196. func (c *Context) postForm(key string) (string, bool) {
  197. req := c.Request
  198. req.ParseMultipartForm(32 << 20) // 32 MB
  199. if values, ok := req.PostForm[key]; ok && len(values) > 0 {
  200. return values[0], true
  201. }
  202. if values, ok := req.MultipartForm.Value[key]; ok && len(values) > 0 {
  203. return values[0], true
  204. }
  205. return "", false
  206. }
  207. // This function 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. // else --> 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. 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.
  213. func (c *Context) Bind(obj interface{}) error {
  214. b := binding.Default(c.Request.Method, c.ContentType())
  215. return c.BindWith(obj, b)
  216. }
  217. func (c *Context) BindJSON(obj interface{}) error {
  218. return c.BindWith(obj, binding.JSON)
  219. }
  220. func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
  221. if err := b.Bind(c.Request, obj); err != nil {
  222. c.AbortWithError(400, err).SetType(ErrorTypeBind)
  223. return err
  224. }
  225. return nil
  226. }
  227. func (c *Context) ClientIP() string {
  228. clientIP := strings.TrimSpace(c.Request.Header.Get("X-Real-IP"))
  229. if len(clientIP) > 0 {
  230. return clientIP
  231. }
  232. clientIP = c.Request.Header.Get("X-Forwarded-For")
  233. clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
  234. if len(clientIP) > 0 {
  235. return clientIP
  236. }
  237. return strings.TrimSpace(c.Request.RemoteAddr)
  238. }
  239. func (c *Context) ContentType() string {
  240. return filterFlags(c.Request.Header.Get("Content-Type"))
  241. }
  242. /************************************/
  243. /******** RESPONSE RENDERING ********/
  244. /************************************/
  245. func (c *Context) Header(key, value string) {
  246. if len(value) == 0 {
  247. c.Writer.Header().Del(key)
  248. } else {
  249. c.Writer.Header().Set(key, value)
  250. }
  251. }
  252. func (c *Context) Render(code int, r render.Render) {
  253. c.Writer.WriteHeader(code)
  254. if err := r.Write(c.Writer); err != nil {
  255. debugPrintError(err)
  256. c.AbortWithError(500, err).SetType(ErrorTypeRender)
  257. }
  258. }
  259. // Renders the HTTP template specified by its file name.
  260. // It also updates the HTTP code and sets the Content-Type as "text/html".
  261. // See http://golang.org/doc/articles/wiki/
  262. func (c *Context) HTML(code int, name string, obj interface{}) {
  263. instance := c.engine.HTMLRender.Instance(name, obj)
  264. c.Render(code, instance)
  265. }
  266. func (c *Context) IndentedJSON(code int, obj interface{}) {
  267. c.Render(code, render.IndentedJSON{Data: obj})
  268. }
  269. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  270. // It also sets the Content-Type as "application/json".
  271. func (c *Context) JSON(code int, obj interface{}) {
  272. c.Render(code, render.JSON{Data: obj})
  273. }
  274. // Serializes the given struct as XML into the response body in a fast and efficient way.
  275. // It also sets the Content-Type as "application/xml".
  276. func (c *Context) XML(code int, obj interface{}) {
  277. c.Render(code, render.XML{Data: obj})
  278. }
  279. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  280. func (c *Context) String(code int, format string, values ...interface{}) {
  281. c.Render(code, render.String{
  282. Format: format,
  283. Data: values},
  284. )
  285. }
  286. // Returns a HTTP redirect to the specific location.
  287. func (c *Context) Redirect(code int, location string) {
  288. c.Render(-1, render.Redirect{
  289. Code: code,
  290. Location: location,
  291. Request: c.Request,
  292. })
  293. }
  294. // Writes some data into the body stream and updates the HTTP code.
  295. func (c *Context) Data(code int, contentType string, data []byte) {
  296. c.Render(code, render.Data{
  297. ContentType: contentType,
  298. Data: data,
  299. })
  300. }
  301. // Writes the specified file into the body stream
  302. func (c *Context) File(filepath string) {
  303. http.ServeFile(c.Writer, c.Request, filepath)
  304. }
  305. func (c *Context) SSEvent(name string, message interface{}) {
  306. c.Render(-1, sse.Event{
  307. Event: name,
  308. Data: message,
  309. })
  310. }
  311. func (c *Context) Stream(step func(w io.Writer) bool) {
  312. w := c.Writer
  313. clientGone := w.CloseNotify()
  314. for {
  315. select {
  316. case <-clientGone:
  317. return
  318. default:
  319. keepopen := step(w)
  320. w.Flush()
  321. if !keepopen {
  322. return
  323. }
  324. }
  325. }
  326. }
  327. /************************************/
  328. /******** CONTENT NEGOTIATION *******/
  329. /************************************/
  330. type Negotiate struct {
  331. Offered []string
  332. HTMLName string
  333. HTMLData interface{}
  334. JSONData interface{}
  335. XMLData interface{}
  336. Data interface{}
  337. }
  338. func (c *Context) Negotiate(code int, config Negotiate) {
  339. switch c.NegotiateFormat(config.Offered...) {
  340. case binding.MIMEJSON:
  341. data := chooseData(config.JSONData, config.Data)
  342. c.JSON(code, data)
  343. case binding.MIMEHTML:
  344. data := chooseData(config.HTMLData, config.Data)
  345. c.HTML(code, config.HTMLName, data)
  346. case binding.MIMEXML:
  347. data := chooseData(config.XMLData, config.Data)
  348. c.XML(code, data)
  349. default:
  350. c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  351. }
  352. }
  353. func (c *Context) NegotiateFormat(offered ...string) string {
  354. if len(offered) == 0 {
  355. panic("you must provide at least one offer")
  356. }
  357. if c.Accepted == nil {
  358. c.Accepted = parseAccept(c.Request.Header.Get("Accept"))
  359. }
  360. if len(c.Accepted) == 0 {
  361. return offered[0]
  362. }
  363. for _, accepted := range c.Accepted {
  364. for _, offert := range offered {
  365. if accepted == offert {
  366. return offert
  367. }
  368. }
  369. }
  370. return ""
  371. }
  372. func (c *Context) SetAccepted(formats ...string) {
  373. c.Accepted = formats
  374. }
  375. /************************************/
  376. /***** GOLANG.ORG/X/NET/CONTEXT *****/
  377. /************************************/
  378. func (c *Context) Deadline() (deadline time.Time, ok bool) {
  379. return
  380. }
  381. func (c *Context) Done() <-chan struct{} {
  382. return nil
  383. }
  384. func (c *Context) Err() error {
  385. return nil
  386. }
  387. func (c *Context) Value(key interface{}) interface{} {
  388. if key == 0 {
  389. return c.Request
  390. }
  391. if keyAsString, ok := key.(string); ok {
  392. val, _ := c.Get(keyAsString)
  393. return val
  394. }
  395. return nil
  396. }