context.go 11 KB

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