Skip to content

Commit

Permalink
Use IndexByte instead of Split to reduce memory allocation and improv…
Browse files Browse the repository at this point in the history
…e performance
  • Loading branch information
yonbiaoxiao committed Sep 15, 2020
1 parent 151ed6b commit 401db93
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
5 changes: 4 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,10 @@ 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]
}
}
if ip := c.request.Header.Get(HeaderXRealIP); ip != "" {
return ip
Expand Down
9 changes: 9 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}

0 comments on commit 401db93

Please sign in to comment.