From c1719f7e2063acd931be65aae2c8bad27f2fc137 Mon Sep 17 00:00:00 2001 From: Donn Pebe Date: Thu, 2 Jul 2015 01:48:21 +0700 Subject: [PATCH] Use only the ip part of request RemoteAddr --- context.go | 6 +++++- context_test.go | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/context.go b/context.go index 12920fd..8948a9f 100644 --- a/context.go +++ b/context.go @@ -8,6 +8,7 @@ import ( "errors" "io" "math" + "net" "net/http" "strings" "time" @@ -269,7 +270,10 @@ func (c *Context) ClientIP() string { return clientIP } } - return strings.TrimSpace(c.Request.RemoteAddr) + if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil { + return ip + } + return "" } func (c *Context) ContentType() string { diff --git a/context_test.go b/context_test.go index 9b78992..9d1fc54 100644 --- a/context_test.go +++ b/context_test.go @@ -478,7 +478,7 @@ func TestContextClientIP(t *testing.T) { c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ") c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30") - c.Request.RemoteAddr = " 40.40.40.40 " + c.Request.RemoteAddr = " 40.40.40.40:42123 " assert.Equal(t, c.ClientIP(), "10.10.10.10")