context.go 12 KB

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