From 622f5e33d4ec32aee7c74d0ecd5339ebe1445f7b Mon Sep 17 00:00:00 2001 From: yonbiaoxiao Date: Tue, 15 Sep 2020 16:58:05 +0800 Subject: [PATCH 1/2] Use IndexByte instead of Split to reduce memory allocation and improve performance --- context.go | 6 +++++- context_test.go | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 99ef03bc..0507f139 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 73e5dcb6..56ac4beb 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() + } +} From 64c49509963da87bb45f32ec239995933798e5a6 Mon Sep 17 00:00:00 2001 From: yonbiaoxiao Date: Wed, 16 Sep 2020 10:36:43 +0800 Subject: [PATCH 2/2] improve the test coverage for context.go --- context_test.go | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/context_test.go b/context_test.go index 56ac4beb..0044bf87 100644 --- a/context_test.go +++ b/context_test.go @@ -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) } @@ -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{ @@ -871,12 +888,3 @@ 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() - } -}