diff --git a/context.go b/context.go index 99ef03bcb..0507f1390 100644 --- a/context.go +++ b/context.go @@ -276,7 +276,11 @@ func (c *context) RealIP() string { } // Fall back to legacy behavior if ip := c.request.Header.Get(HeaderXForwardedFor); ip != "" { - return strings.Split(ip, ", ")[0] + i := strings.IndexAny(ip, ", ") + if i > 0 { + return ip[:i] + } + return ip } if ip := c.request.Header.Get(HeaderXRealIP); ip != "" { return ip diff --git a/context_test.go b/context_test.go index 73e5dcb62..56ac4bebf 100644 --- a/context_test.go +++ b/context_test.go @@ -871,3 +871,12 @@ func TestContext_RealIP(t *testing.T) { testify.Equal(t, tt.s, tt.c.RealIP()) } } + +func BenchmarkRealIPForHeaderXForwardFor(b *testing.B) { + c := context{request: &http.Request{ + Header: http.Header{HeaderXForwardedFor: []string{"127.0.0.1, 127.0.1.1, "}}, + }} + for i := 0; i < b.N; i++ { + c.RealIP() + } +}