Skip to content

Commit

Permalink
Merge pull request #1640 from imxyb/feature/opt-split
Browse files Browse the repository at this point in the history
Use IndexAny instead of Split to reduce memory allocation
  • Loading branch information
lammel committed Nov 5, 2020
2 parents 151ed6b + 64c4950 commit 095af21
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
6 changes: 5 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@ func BenchmarkAllocXML(b *testing.B) {
}
}

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()
}
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
Expand Down Expand Up @@ -847,6 +856,14 @@ func TestContext_RealIP(t *testing.T) {
},
"127.0.0.1",
},
{
&context{
request: &http.Request{
Header: http.Header{HeaderXForwardedFor: []string{"127.0.0.1"}},
},
},
"127.0.0.1",
},
{
&context{
request: &http.Request{
Expand Down

0 comments on commit 095af21

Please sign in to comment.