context.go 12 KB

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