Kaynağa Gözat

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

Frédéric Guillot 7 yıl önce
ebeveyn
işleme
9f85f67031
2 değiştirilmiş dosya ile 25 ekleme ve 0 silme
  1. 5 0
      http/request/client_ip.go
  2. 20 0
      http/request/client_ip_test.go

+ 5 - 0
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
 }

+ 20 - 0
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)
+	}
+}