Make sure the remote address is populated even when using unix socket

This commit is contained in:
Frédéric Guillot 2018-11-11 16:42:30 -08:00
parent 1315282c7f
commit 9f85f67031
2 changed files with 25 additions and 0 deletions

View File

@ -34,5 +34,10 @@ func FindClientIP(r *http.Request) string {
remoteIP = r.RemoteAddr
}
// When listening on a Unix socket, RemoteAddr is empty.
if remoteIP == "" {
remoteIP = "127.0.0.1"
}
return remoteIP
}

View File

@ -80,3 +80,23 @@ func TestClientIPWithBothHeaders(t *testing.T) {
t.Fatalf(`Unexpected result, got: %q`, ip)
}
}
func TestClientIPWithNoRemoteAddress(t *testing.T) {
r := &http.Request{}
if ip := FindClientIP(r); ip != "127.0.0.1" {
t.Fatalf(`Unexpected result, got: %q`, ip)
}
}
func TestClientIPWithoutRemoteAddrAndBothHeaders(t *testing.T) {
headers := http.Header{}
headers.Set("X-Forwarded-For", "203.0.113.195, 70.41.3.18, 150.172.238.178")
headers.Set("X-Real-Ip", "192.168.122.1")
r := &http.Request{RemoteAddr: "", Header: headers}
if ip := FindClientIP(r); ip != "203.0.113.195" {
t.Fatalf(`Unexpected result, got: %q`, ip)
}
}