Skip to content

Commit 42ef920

Browse files
author
yonbiaoxiao
committed
Use IndexByte instead of Split to reduce memory allocation and improve performance
1 parent 151ed6b commit 42ef920

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

context.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,12 @@ func (c *context) RealIP() string {
276276
}
277277
// Fall back to legacy behavior
278278
if ip := c.request.Header.Get(HeaderXForwardedFor); ip != "" {
279-
return strings.Split(ip, ", ")[0]
279+
i := strings.IndexAny(ip, ", ")
280+
if i > 0 {
281+
return ip[:i]
282+
} else {
283+
return ip
284+
}
280285
}
281286
if ip := c.request.Header.Get(HeaderXRealIP); ip != "" {
282287
return ip

context_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -871,3 +871,12 @@ func TestContext_RealIP(t *testing.T) {
871871
testify.Equal(t, tt.s, tt.c.RealIP())
872872
}
873873
}
874+
875+
func BenchmarkRealIPForHeaderXForwardFor(b *testing.B) {
876+
c := context{request: &http.Request{
877+
Header: http.Header{HeaderXForwardedFor: []string{"127.0.0.1, 127.0.1.1, "}},
878+
}}
879+
for i := 0; i < b.N; i++ {
880+
c.RealIP()
881+
}
882+
}

0 commit comments

Comments
 (0)