context.go 11 KB

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