context.go 12 KB

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