From 6bf060f179e4706d5ad994e35e4cea4ef9f9ab04 Mon Sep 17 00:00:00 2001 From: Philipp Meinen Date: Sat, 25 Jul 2015 20:39:05 +0200 Subject: [PATCH] Context.ClientIP(): only return the host's ip address http.Request.RemoteAddr contains the client's ip address and port number. The reverse proxy headers X-Real-Ip and X-Forwarded-For usually only contain a client's ip address. This change ensures that the ClientIP method behaves the same in both situations. The additional logic results in one more allocation. BenchmarkLoggerMiddleware is affected and goes from 14 to 15 allocations. --- context.go | 9 ++++++++- context_test.go | 3 +++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index b784c14b..28103c77 100644 --- a/context.go +++ b/context.go @@ -8,6 +8,7 @@ import ( "errors" "io" "math" + "net" "net/http" "strings" "time" @@ -291,7 +292,13 @@ func (c *Context) ClientIP() string { return clientIP } } - return strings.TrimSpace(c.Request.RemoteAddr) + + // http.Request.RemoteAddr also contains the connection's port number; only return the client's ip + host, _, err := net.SplitHostPort(c.Request.RemoteAddr) + if err != nil { + host = c.Request.RemoteAddr + } + return strings.TrimSpace(host) } // ContentType returns the Content-Type header of the request. diff --git a/context_test.go b/context_test.go index efdba7b2..2e2aaca2 100644 --- a/context_test.go +++ b/context_test.go @@ -531,6 +531,9 @@ func TestContextClientIP(t *testing.T) { c.Request.Header.Del("X-Forwarded-For") assert.Equal(t, c.ClientIP(), "40.40.40.40") + + c.Request.RemoteAddr = " 40.40.40.40:12345 " + assert.Equal(t, c.ClientIP(), "40.40.40.40") } func TestContextContentType(t *testing.T) {