fix error

This commit is contained in:
thinkerou 2021-03-27 11:32:49 +08:00
parent 7e649c347f
commit 08766787f9
3 changed files with 38 additions and 30 deletions

View File

@ -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
}

View File

@ -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
View File

@ -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, "/") {
@ -362,8 +365,6 @@ func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {
}
return cidr, nil
}
return nil, nil
}
// parseIP parse a string representation of an IP and returns a net.IP with the
// minimum byte representation or nil if input is invalid.