context.go 12 KB

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