context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. var _ context.Context = &Context{}
  28. // Param is a single URL parameter, consisting of a key and a value.
  29. type Param struct {
  30. Key string
  31. Value string
  32. }
  33. // Params is a Param-slice, as returned by the router.
  34. // The slice is ordered, the first URL parameter is also the first slice value.
  35. // It is therefore safe to read values by the index.
  36. type Params []Param
  37. // ByName returns the value of the first Param which key matches the given name.
  38. // If no matching Param is found, an empty string is returned.
  39. func (ps Params) Get(name string) (string, bool) {
  40. for _, entry := range ps {
  41. if entry.Key == name {
  42. return entry.Value, true
  43. }
  44. }
  45. return "", false
  46. }
  47. func (ps Params) ByName(name string) (va string) {
  48. va, _ = ps.Get(name)
  49. return
  50. }
  51. // Context is the most important part of gin. It allows us to pass variables between middleware,
  52. // manage the flow, validate the JSON of a request and render a JSON response for example.
  53. type Context struct {
  54. writermem responseWriter
  55. Request *http.Request
  56. Writer ResponseWriter
  57. Params Params
  58. handlers HandlersChain
  59. index int8
  60. engine *Engine
  61. Keys map[string]interface{}
  62. Errors errorMsgs
  63. Accepted []string
  64. }
  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.FormValue(key) */
  164. func (c *Context) FormValue(key string) (va string) {
  165. va, _ = c.formValue(key)
  166. return
  167. }
  168. /** Shortcut for c.Request.PostFormValue(key) */
  169. func (c *Context) PostFormValue(key string) (va string) {
  170. va, _ = c.postFormValue(key)
  171. return
  172. }
  173. /** Shortcut for c.Params.ByName(key) */
  174. func (c *Context) ParamValue(key string) (va string) {
  175. va, _ = c.paramValue(key)
  176. return
  177. }
  178. func (c *Context) DefaultPostFormValue(key, defaultValue string) string {
  179. if va, ok := c.postFormValue(key); ok {
  180. return va
  181. }
  182. return defaultValue
  183. }
  184. func (c *Context) DefaultFormValue(key, defaultValue string) string {
  185. if va, ok := c.formValue(key); ok {
  186. return va
  187. }
  188. return defaultValue
  189. }
  190. func (c *Context) DefaultParamValue(key, defaultValue string) string {
  191. if va, ok := c.paramValue(key); ok {
  192. return va
  193. }
  194. return defaultValue
  195. }
  196. func (c *Context) paramValue(key string) (string, bool) {
  197. return c.Params.Get(key)
  198. }
  199. func (c *Context) formValue(key string) (string, bool) {
  200. req := c.Request
  201. req.ParseForm()
  202. if values, ok := req.Form[key]; ok && len(values) > 0 {
  203. return values[0], true
  204. }
  205. return "", false
  206. }
  207. func (c *Context) postFormValue(key string) (string, bool) {
  208. req := c.Request
  209. req.ParseForm()
  210. if values, ok := req.PostForm[key]; ok && len(values) > 0 {
  211. return values[0], true
  212. }
  213. return "", false
  214. }
  215. // This function checks the Content-Type to select a binding engine automatically,
  216. // Depending the "Content-Type" header different bindings are used:
  217. // "application/json" --> JSON binding
  218. // "application/xml" --> XML binding
  219. // else --> returns an error
  220. // 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.
  221. func (c *Context) Bind(obj interface{}) error {
  222. b := binding.Default(c.Request.Method, c.ContentType())
  223. return c.BindWith(obj, b)
  224. }
  225. func (c *Context) BindJSON(obj interface{}) error {
  226. return c.BindWith(obj, binding.JSON)
  227. }
  228. func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
  229. if err := b.Bind(c.Request, obj); err != nil {
  230. c.AbortWithError(400, err).SetType(ErrorTypeBind)
  231. return err
  232. }
  233. return nil
  234. }
  235. func (c *Context) ClientIP() string {
  236. clientIP := strings.TrimSpace(c.Request.Header.Get("X-Real-IP"))
  237. if len(clientIP) > 0 {
  238. return clientIP
  239. }
  240. clientIP = c.Request.Header.Get("X-Forwarded-For")
  241. clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
  242. if len(clientIP) > 0 {
  243. return clientIP
  244. }
  245. return strings.TrimSpace(c.Request.RemoteAddr)
  246. }
  247. func (c *Context) ContentType() string {
  248. return filterFlags(c.Request.Header.Get("Content-Type"))
  249. }
  250. /************************************/
  251. /******** RESPONSE RENDERING ********/
  252. /************************************/
  253. func (c *Context) Header(key, value string) {
  254. if len(value) == 0 {
  255. c.Writer.Header().Del(key)
  256. } else {
  257. c.Writer.Header().Set(key, value)
  258. }
  259. }
  260. func (c *Context) Render(code int, r render.Render) {
  261. c.Writer.WriteHeader(code)
  262. if err := r.Write(c.Writer); err != nil {
  263. debugPrintError(err)
  264. c.AbortWithError(500, err).SetType(ErrorTypeRender)
  265. }
  266. }
  267. // Renders the HTTP template specified by its file name.
  268. // It also updates the HTTP code and sets the Content-Type as "text/html".
  269. // See http://golang.org/doc/articles/wiki/
  270. func (c *Context) HTML(code int, name string, obj interface{}) {
  271. instance := c.engine.HTMLRender.Instance(name, obj)
  272. c.Render(code, instance)
  273. }
  274. func (c *Context) IndentedJSON(code int, obj interface{}) {
  275. c.Render(code, render.IndentedJSON{Data: obj})
  276. }
  277. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  278. // It also sets the Content-Type as "application/json".
  279. func (c *Context) JSON(code int, obj interface{}) {
  280. c.Render(code, render.JSON{Data: obj})
  281. }
  282. // Serializes the given struct as XML into the response body in a fast and efficient way.
  283. // It also sets the Content-Type as "application/xml".
  284. func (c *Context) XML(code int, obj interface{}) {
  285. c.Render(code, render.XML{Data: obj})
  286. }
  287. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  288. func (c *Context) String(code int, format string, values ...interface{}) {
  289. c.Render(code, render.String{
  290. Format: format,
  291. Data: values},
  292. )
  293. }
  294. // Returns a HTTP redirect to the specific location.
  295. func (c *Context) Redirect(code int, location string) {
  296. c.Render(-1, render.Redirect{
  297. Code: code,
  298. Location: location,
  299. Request: c.Request,
  300. })
  301. }
  302. // Writes some data into the body stream and updates the HTTP code.
  303. func (c *Context) Data(code int, contentType string, data []byte) {
  304. c.Render(code, render.Data{
  305. ContentType: contentType,
  306. Data: data,
  307. })
  308. }
  309. // Writes the specified file into the body stream
  310. func (c *Context) File(filepath string) {
  311. http.ServeFile(c.Writer, c.Request, filepath)
  312. }
  313. func (c *Context) SSEvent(name string, message interface{}) {
  314. c.Render(-1, sse.Event{
  315. Event: name,
  316. Data: message,
  317. })
  318. }
  319. func (c *Context) Stream(step func(w io.Writer) bool) {
  320. w := c.Writer
  321. clientGone := w.CloseNotify()
  322. for {
  323. select {
  324. case <-clientGone:
  325. return
  326. default:
  327. keepopen := step(w)
  328. w.Flush()
  329. if !keepopen {
  330. return
  331. }
  332. }
  333. }
  334. }
  335. /************************************/
  336. /******** CONTENT NEGOTIATION *******/
  337. /************************************/
  338. type Negotiate struct {
  339. Offered []string
  340. HTMLName string
  341. HTMLData interface{}
  342. JSONData interface{}
  343. XMLData interface{}
  344. Data interface{}
  345. }
  346. func (c *Context) Negotiate(code int, config Negotiate) {
  347. switch c.NegotiateFormat(config.Offered...) {
  348. case binding.MIMEJSON:
  349. data := chooseData(config.JSONData, config.Data)
  350. c.JSON(code, data)
  351. case binding.MIMEHTML:
  352. data := chooseData(config.HTMLData, config.Data)
  353. c.HTML(code, config.HTMLName, data)
  354. case binding.MIMEXML:
  355. data := chooseData(config.XMLData, config.Data)
  356. c.XML(code, data)
  357. default:
  358. c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  359. }
  360. }
  361. func (c *Context) NegotiateFormat(offered ...string) string {
  362. if len(offered) == 0 {
  363. panic("you must provide at least one offer")
  364. }
  365. if c.Accepted == nil {
  366. c.Accepted = parseAccept(c.Request.Header.Get("Accept"))
  367. }
  368. if len(c.Accepted) == 0 {
  369. return offered[0]
  370. }
  371. for _, accepted := range c.Accepted {
  372. for _, offert := range offered {
  373. if accepted == offert {
  374. return offert
  375. }
  376. }
  377. }
  378. return ""
  379. }
  380. func (c *Context) SetAccepted(formats ...string) {
  381. c.Accepted = formats
  382. }
  383. /************************************/
  384. /******** CONTENT NEGOTIATION *******/
  385. /************************************/
  386. func (c *Context) Deadline() (deadline time.Time, ok bool) {
  387. return
  388. }
  389. func (c *Context) Done() <-chan struct{} {
  390. return nil
  391. }
  392. func (c *Context) Err() error {
  393. return nil
  394. }
  395. func (c *Context) Value(key interface{}) interface{} {
  396. if key == 0 {
  397. return c.Request
  398. }
  399. if keyAsString, ok := key.(string); ok {
  400. val, _ := c.Get(keyAsString)
  401. return val
  402. }
  403. return nil
  404. }