context.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. "bytes"
  7. "errors"
  8. "fmt"
  9. "github.com/gin-gonic/gin/binding"
  10. "github.com/gin-gonic/gin/render"
  11. "github.com/julienschmidt/httprouter"
  12. "log"
  13. "net"
  14. "net/http"
  15. "strings"
  16. )
  17. const (
  18. ErrorTypeInternal = 1 << iota
  19. ErrorTypeExternal = 1 << iota
  20. ErrorTypeAll = 0xffffffff
  21. )
  22. // Used internally to collect errors that occurred during an http request.
  23. type errorMsg struct {
  24. Err string `json:"error"`
  25. Type uint32 `json:"-"`
  26. Meta interface{} `json:"meta"`
  27. }
  28. type errorMsgs []errorMsg
  29. func (a errorMsgs) ByType(typ uint32) errorMsgs {
  30. if len(a) == 0 {
  31. return a
  32. }
  33. result := make(errorMsgs, 0, len(a))
  34. for _, msg := range a {
  35. if msg.Type&typ > 0 {
  36. result = append(result, msg)
  37. }
  38. }
  39. return result
  40. }
  41. func (a errorMsgs) String() string {
  42. if len(a) == 0 {
  43. return ""
  44. }
  45. var buffer bytes.Buffer
  46. for i, msg := range a {
  47. text := fmt.Sprintf("Error #%02d: %s \n Meta: %v\n", (i + 1), msg.Err, msg.Meta)
  48. buffer.WriteString(text)
  49. }
  50. return buffer.String()
  51. }
  52. // Context is the most important part of gin. It allows us to pass variables between middleware,
  53. // manage the flow, validate the JSON of a request and render a JSON response for example.
  54. type Context struct {
  55. writermem responseWriter
  56. Request *http.Request
  57. Writer ResponseWriter
  58. Keys map[string]interface{}
  59. Errors errorMsgs
  60. Params httprouter.Params
  61. Engine *Engine
  62. handlers []HandlerFunc
  63. index int8
  64. accepted []string
  65. }
  66. /************************************/
  67. /********** CONTEXT CREATION ********/
  68. /************************************/
  69. func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
  70. c := engine.pool.Get().(*Context)
  71. c.writermem.reset(w)
  72. c.Request = req
  73. c.Params = params
  74. c.handlers = handlers
  75. c.Keys = nil
  76. c.index = -1
  77. c.accepted = nil
  78. c.Errors = c.Errors[0:0]
  79. return c
  80. }
  81. func (engine *Engine) reuseContext(c *Context) {
  82. engine.pool.Put(c)
  83. }
  84. func (c *Context) Copy() *Context {
  85. var cp Context = *c
  86. cp.index = AbortIndex
  87. cp.handlers = nil
  88. return &cp
  89. }
  90. /************************************/
  91. /*************** FLOW ***************/
  92. /************************************/
  93. // Next should be used only in the middlewares.
  94. // It executes the pending handlers in the chain inside the calling handler.
  95. // See example in github.
  96. func (c *Context) Next() {
  97. c.index++
  98. s := int8(len(c.handlers))
  99. for ; c.index < s; c.index++ {
  100. c.handlers[c.index](c)
  101. }
  102. }
  103. // Forces the system to do not continue calling the pending handlers in the chain.
  104. func (c *Context) Abort() {
  105. c.index = AbortIndex
  106. }
  107. // Same than AbortWithStatus() but also writes the specified response status code.
  108. // For example, the first handler checks if the request is authorized. If it's not, context.AbortWithStatus(401) should be called.
  109. func (c *Context) AbortWithStatus(code int) {
  110. c.Writer.WriteHeader(code)
  111. c.Abort()
  112. }
  113. /************************************/
  114. /********* ERROR MANAGEMENT *********/
  115. /************************************/
  116. // Fail is the same as Abort plus an error message.
  117. // Calling `context.Fail(500, err)` is equivalent to:
  118. // ```
  119. // context.Error("Operation aborted", err)
  120. // context.AbortWithStatus(500)
  121. // ```
  122. func (c *Context) Fail(code int, err error) {
  123. c.Error(err, "Operation aborted")
  124. c.AbortWithStatus(code)
  125. }
  126. func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {
  127. c.Errors = append(c.Errors, errorMsg{
  128. Err: err.Error(),
  129. Type: typ,
  130. Meta: meta,
  131. })
  132. }
  133. // Attaches an error to the current context. The error is pushed to a list of errors.
  134. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  135. // 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.
  136. func (c *Context) Error(err error, meta interface{}) {
  137. c.ErrorTyped(err, ErrorTypeExternal, meta)
  138. }
  139. func (c *Context) LastError() error {
  140. nuErrors := len(c.Errors)
  141. if nuErrors > 0 {
  142. return errors.New(c.Errors[nuErrors-1].Err)
  143. } else {
  144. return nil
  145. }
  146. }
  147. /************************************/
  148. /******** METADATA MANAGEMENT********/
  149. /************************************/
  150. // Sets a new pair key/value just for the specified context.
  151. // It also lazy initializes the hashmap.
  152. func (c *Context) Set(key string, item interface{}) {
  153. if c.Keys == nil {
  154. c.Keys = make(map[string]interface{})
  155. }
  156. c.Keys[key] = item
  157. }
  158. // Get returns the value for the given key or an error if the key does not exist.
  159. func (c *Context) Get(key string) (interface{}, error) {
  160. if c.Keys != nil {
  161. value, ok := c.Keys[key]
  162. if ok {
  163. return value, nil
  164. }
  165. }
  166. return nil, errors.New("Key does not exist.")
  167. }
  168. // MustGet returns the value for the given key or panics if the value doesn't exist.
  169. func (c *Context) MustGet(key string) interface{} {
  170. value, err := c.Get(key)
  171. if err != nil || value == nil {
  172. log.Panicf("Key %s doesn't exist", value)
  173. }
  174. return value
  175. }
  176. func ipInMasks(ip net.IP, masks []interface{}) bool {
  177. for _, proxy := range masks {
  178. var mask *net.IPNet
  179. var err error
  180. switch t := proxy.(type) {
  181. case string:
  182. if _, mask, err = net.ParseCIDR(t); err != nil {
  183. panic(err)
  184. }
  185. case net.IP:
  186. mask = &net.IPNet{IP: t, Mask: net.CIDRMask(len(t)*8, len(t)*8)}
  187. case net.IPNet:
  188. mask = &t
  189. }
  190. if mask.Contains(ip) {
  191. return true
  192. }
  193. }
  194. return false
  195. }
  196. // the ForwardedFor middleware unwraps the X-Forwarded-For headers, be careful to only use this
  197. // middleware if you've got servers in front of this server. The list with (known) proxies and
  198. // local ips are being filtered out of the forwarded for list, giving the last not local ip being
  199. // the real client ip.
  200. func ForwardedFor(proxies ...interface{}) HandlerFunc {
  201. if len(proxies) == 0 {
  202. // default to local ips
  203. var reservedLocalIps = []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
  204. proxies = make([]interface{}, len(reservedLocalIps))
  205. for i, v := range reservedLocalIps {
  206. proxies[i] = v
  207. }
  208. }
  209. return func(c *Context) {
  210. // the X-Forwarded-For header contains an array with left most the client ip, then
  211. // comma separated, all proxies the request passed. The last proxy appears
  212. // as the remote address of the request. Returning the client
  213. // ip to comply with default RemoteAddr response.
  214. // check if remoteaddr is local ip or in list of defined proxies
  215. remoteIp := net.ParseIP(strings.Split(c.Request.RemoteAddr, ":")[0])
  216. if !ipInMasks(remoteIp, proxies) {
  217. return
  218. }
  219. if forwardedFor := c.Request.Header.Get("X-Forwarded-For"); forwardedFor != "" {
  220. parts := strings.Split(forwardedFor, ",")
  221. for i := len(parts) - 1; i >= 0; i-- {
  222. part := parts[i]
  223. ip := net.ParseIP(strings.TrimSpace(part))
  224. if ipInMasks(ip, proxies) {
  225. continue
  226. }
  227. // returning remote addr conform the original remote addr format
  228. c.Request.RemoteAddr = ip.String() + ":0"
  229. // remove forwarded for address
  230. c.Request.Header.Set("X-Forwarded-For", "")
  231. return
  232. }
  233. }
  234. }
  235. }
  236. func (c *Context) ClientIP() string {
  237. return c.Request.RemoteAddr
  238. }
  239. /************************************/
  240. /********* PARSING REQUEST **********/
  241. /************************************/
  242. // This function checks the Content-Type to select a binding engine automatically,
  243. // Depending the "Content-Type" header different bindings are used:
  244. // "application/json" --> JSON binding
  245. // "application/xml" --> XML binding
  246. // else --> returns an error
  247. // 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.
  248. func (c *Context) Bind(obj interface{}) bool {
  249. var b binding.Binding
  250. ctype := filterFlags(c.Request.Header.Get("Content-Type"))
  251. switch {
  252. case c.Request.Method == "GET" || ctype == MIMEPOSTForm:
  253. b = binding.Form
  254. case ctype == MIMEJSON:
  255. b = binding.JSON
  256. case ctype == MIMEXML || ctype == MIMEXML2:
  257. b = binding.XML
  258. default:
  259. c.Fail(400, errors.New("unknown content-type: "+ctype))
  260. return false
  261. }
  262. return c.BindWith(obj, b)
  263. }
  264. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  265. if err := b.Bind(c.Request, obj); err != nil {
  266. c.Fail(400, err)
  267. return false
  268. }
  269. return true
  270. }
  271. /************************************/
  272. /******** RESPONSE RENDERING ********/
  273. /************************************/
  274. func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  275. if err := render.Render(c.Writer, code, obj...); err != nil {
  276. c.ErrorTyped(err, ErrorTypeInternal, obj)
  277. c.AbortWithStatus(500)
  278. }
  279. }
  280. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  281. // It also sets the Content-Type as "application/json".
  282. func (c *Context) JSON(code int, obj interface{}) {
  283. c.Render(code, render.JSON, obj)
  284. }
  285. // Serializes the given struct as XML into the response body in a fast and efficient way.
  286. // It also sets the Content-Type as "application/xml".
  287. func (c *Context) XML(code int, obj interface{}) {
  288. c.Render(code, render.XML, obj)
  289. }
  290. // Renders the HTTP template specified by its file name.
  291. // It also updates the HTTP code and sets the Content-Type as "text/html".
  292. // See http://golang.org/doc/articles/wiki/
  293. func (c *Context) HTML(code int, name string, obj interface{}) {
  294. c.Render(code, c.Engine.HTMLRender, name, obj)
  295. }
  296. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  297. func (c *Context) String(code int, format string, values ...interface{}) {
  298. c.Render(code, render.Plain, format, values)
  299. }
  300. // Returns a HTTP redirect to the specific location.
  301. func (c *Context) Redirect(code int, location string) {
  302. if code >= 300 && code <= 308 {
  303. c.Render(code, render.Redirect, location)
  304. } else {
  305. panic(fmt.Sprintf("Cannot send a redirect with status code %d", code))
  306. }
  307. }
  308. // Writes some data into the body stream and updates the HTTP code.
  309. func (c *Context) Data(code int, contentType string, data []byte) {
  310. if len(contentType) > 0 {
  311. c.Writer.Header().Set("Content-Type", contentType)
  312. }
  313. c.Writer.WriteHeader(code)
  314. c.Writer.Write(data)
  315. }
  316. // Writes the specified file into the body stream
  317. func (c *Context) File(filepath string) {
  318. http.ServeFile(c.Writer, c.Request, filepath)
  319. }
  320. /************************************/
  321. /******** CONTENT NEGOTIATION *******/
  322. /************************************/
  323. type Negotiate struct {
  324. Offered []string
  325. HTMLPath string
  326. HTMLData interface{}
  327. JSONData interface{}
  328. XMLData interface{}
  329. Data interface{}
  330. }
  331. func (c *Context) Negotiate(code int, config Negotiate) {
  332. switch c.NegotiateFormat(config.Offered...) {
  333. case MIMEJSON:
  334. data := chooseData(config.JSONData, config.Data)
  335. c.JSON(code, data)
  336. case MIMEHTML:
  337. data := chooseData(config.HTMLData, config.Data)
  338. if len(config.HTMLPath) == 0 {
  339. panic("negotiate config is wrong. html path is needed")
  340. }
  341. c.HTML(code, config.HTMLPath, data)
  342. case MIMEXML:
  343. data := chooseData(config.XMLData, config.Data)
  344. c.XML(code, data)
  345. default:
  346. c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
  347. }
  348. }
  349. func (c *Context) NegotiateFormat(offered ...string) string {
  350. if len(offered) == 0 {
  351. panic("you must provide at least one offer")
  352. }
  353. if c.accepted == nil {
  354. c.accepted = parseAccept(c.Request.Header.Get("Accept"))
  355. }
  356. if len(c.accepted) == 0 {
  357. return offered[0]
  358. } else {
  359. for _, accepted := range c.accepted {
  360. for _, offert := range offered {
  361. if accepted == offert {
  362. return offert
  363. }
  364. }
  365. }
  366. return ""
  367. }
  368. }
  369. func (c *Context) SetAccepted(formats ...string) {
  370. c.accepted = formats
  371. }