From 9f85f6703116c3d01d3d1b768df22b466d5d3613 Mon Sep 17 00:00:00 2001 From: Frédéric Guillot Date: Sun, 11 Nov 2018 16:42:30 -0800 Subject: Make sure the remote address is populated even when using unix socket --- http/request/client_ip.go | 5 +++++ http/request/client_ip_test.go | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) (limited to 'http') diff --git a/http/request/client_ip.go b/http/request/client_ip.go index 52fc05c..27fb64e 100644 --- a/http/request/client_ip.go +++ b/http/request/client_ip.go @@ -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 } diff --git a/http/request/client_ip_test.go b/http/request/client_ip_test.go index 12d6e16..82f7dd6 100644 --- a/http/request/client_ip_test.go +++ b/http/request/client_ip_test.go @@ -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) + } +} -- cgit v1.2.3