diff --git a/utils/clientId.go b/utils/clientId.go index e40b0d104..38188bcdc 100644 --- a/utils/clientId.go +++ b/utils/clientId.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "net" "net/http" + "strings" log "github.com/sirupsen/logrus" ) @@ -24,7 +25,13 @@ func GetIPAddressFromRequest(req *http.Request) string { ipAddressString := req.RemoteAddr xForwardedFor := req.Header.Get("X-FORWARDED-FOR") if xForwardedFor != "" { - return xForwardedFor + clientIpString := strings.Split(xForwardedFor, ", ")[0] + ip, _, err := net.SplitHostPort(clientIpString) + if err != nil { + log.Errorln(err) + return "" + } + return ip } ip, _, err := net.SplitHostPort(ipAddressString) diff --git a/utils/clientId_test.go b/utils/clientId_test.go new file mode 100644 index 000000000..9af802828 --- /dev/null +++ b/utils/clientId_test.go @@ -0,0 +1,27 @@ +package utils + +import ( + "net/http/httptest" + "testing" +) + +func TestGetIPAddressFromRequest(t *testing.T) { + + expectedResult := "203.0.113.195" + + request := httptest.NewRequest("GET", "/", nil) + request.RemoteAddr = "203.0.113.195:41237" + //First Test without X-FORWARDED-FOR header + result := GetIPAddressFromRequest(request) + if result != expectedResult { + t.Errorf("Remote address only test failed: Expected %s, got %s", expectedResult, result) + } + + //Test with X-FORWARDED-FOR header + request.Header.Set("X-FORWARDED-FOR header", "203.0.113.195:41237, 198.51.100.100:38523, 140.248.67.176:12345") + result = GetIPAddressFromRequest(request) + if result != expectedResult { + t.Errorf("X-FORWARD-FOR header test failed: Expected %s, got %s", expectedResult, result) + } + +}