mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-07-27 05:27:21 +00:00
SplitHostPort is needed since Request.RemoteAddr has the host:port format
This commit is contained in:
parent
e0f7de94f5
commit
b77356afbf
@ -153,8 +153,14 @@ func GetClientIP(req *http.Request) net.IP {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fallback to Remote Address in request, which will give the correct client IP when there is no proxy.
|
// Fallback to Remote Address in request, which will give the correct client IP when there is no proxy.
|
||||||
ip := net.ParseIP(req.RemoteAddr)
|
// Remote Address in Go's HTTP server is in the form host:port so we need to split that first.
|
||||||
return ip
|
host, _, err := net.SplitHostPort(req.RemoteAddr)
|
||||||
|
if err == nil {
|
||||||
|
return net.ParseIP(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback if Remote Address was just IP.
|
||||||
|
return net.ParseIP(req.RemoteAddr)
|
||||||
}
|
}
|
||||||
|
|
||||||
var defaultProxyFuncPointer = fmt.Sprintf("%p", http.ProxyFromEnvironment)
|
var defaultProxyFuncPointer = fmt.Sprintf("%p", http.ProxyFromEnvironment)
|
||||||
|
@ -76,7 +76,8 @@ func TestGetClientIP(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
Request: http.Request{
|
Request: http.Request{
|
||||||
RemoteAddr: ipString,
|
// RemoteAddr is in the form host:port
|
||||||
|
RemoteAddr: ipString + ":1234",
|
||||||
},
|
},
|
||||||
ExpectedIP: ip,
|
ExpectedIP: ip,
|
||||||
},
|
},
|
||||||
@ -90,6 +91,7 @@ func TestGetClientIP(t *testing.T) {
|
|||||||
Header: map[string][]string{
|
Header: map[string][]string{
|
||||||
"X-Forwarded-For": {invalidIPString},
|
"X-Forwarded-For": {invalidIPString},
|
||||||
},
|
},
|
||||||
|
// RemoteAddr is in the form host:port
|
||||||
RemoteAddr: ipString,
|
RemoteAddr: ipString,
|
||||||
},
|
},
|
||||||
ExpectedIP: ip,
|
ExpectedIP: ip,
|
||||||
@ -98,7 +100,7 @@ func TestGetClientIP(t *testing.T) {
|
|||||||
|
|
||||||
for i, test := range testCases {
|
for i, test := range testCases {
|
||||||
if a, e := GetClientIP(&test.Request), test.ExpectedIP; reflect.DeepEqual(e, a) != true {
|
if a, e := GetClientIP(&test.Request), test.ExpectedIP; reflect.DeepEqual(e, a) != true {
|
||||||
t.Fatalf("test case %d failed. expected: %v, actual: %v", i+1, e, a)
|
t.Fatalf("test case %d failed. expected: %v, actual: %v", i, e, a)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user