mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-18 06:42:10 +08:00
fix error
This commit is contained in:
parent
7e649c347f
commit
08766787f9
@ -741,6 +741,7 @@ func (c *Context) ClientIP() string {
|
||||
if remoteIP == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
|
||||
for _, headerName := range c.engine.RemoteIPHeaders {
|
||||
ip, valid := validateHeader(c.requestHeader(headerName))
|
||||
@ -765,6 +766,10 @@ func (c *Context) RemoteIP() (net.IP, bool) {
|
||||
if remoteIP == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
trustedCIDRs, err := c.engine.prepareTrustedCIDRs()
|
||||
if err == nil {
|
||||
c.engine.trustedCIDRs = trustedCIDRs
|
||||
if c.engine.trustedCIDRs != nil {
|
||||
for _, cidr := range c.engine.trustedCIDRs {
|
||||
if cidr.Contains(remoteIP) {
|
||||
@ -772,6 +777,8 @@ func (c *Context) RemoteIP() (net.IP, bool) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return remoteIP, false
|
||||
}
|
||||
|
||||
|
@ -1430,7 +1430,7 @@ func TestContextClientIP(t *testing.T) {
|
||||
|
||||
// Only trust RemoteAddr
|
||||
c.engine.TrustedProxies = []string{"40.40.40.40"}
|
||||
assert.Equal(t, "30.30.30.30", c.ClientIP())
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
|
||||
// All steps are trusted
|
||||
c.engine.TrustedProxies = []string{"40.40.40.40", "30.30.30.30", "20.20.20.20"}
|
||||
@ -1442,7 +1442,7 @@ func TestContextClientIP(t *testing.T) {
|
||||
|
||||
// Use hostname that resolves to all the proxies
|
||||
c.engine.TrustedProxies = []string{"foo"}
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
assert.Equal(t, "40.40.40.40", c.ClientIP())
|
||||
|
||||
// Use hostname that returns an error
|
||||
c.engine.TrustedProxies = []string{"bar"}
|
||||
|
7
gin.go
7
gin.go
@ -338,7 +338,10 @@ func (engine *Engine) Run(addr ...string) (err error) {
|
||||
}
|
||||
|
||||
func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {
|
||||
if engine.TrustedProxies != nil {
|
||||
if engine.TrustedProxies == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
cidr := make([]*net.IPNet, 0, len(engine.TrustedProxies))
|
||||
for _, trustedProxy := range engine.TrustedProxies {
|
||||
if !strings.Contains(trustedProxy, "/") {
|
||||
@ -361,8 +364,6 @@ func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {
|
||||
cidr = append(cidr, cidrNet)
|
||||
}
|
||||
return cidr, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// parseIP parse a string representation of an IP and returns a net.IP with the
|
||||
|
Loading…
x
Reference in New Issue
Block a user