From 0a9030f9d7a42372f8fae1381e3af62db9b9b289 Mon Sep 17 00:00:00 2001 From: Manu Mtz-Almeida Date: Sun, 24 May 2015 15:35:08 +0200 Subject: [PATCH] ClientIP() must trim the white spaces --- context.go | 8 ++++---- context_test.go | 9 ++++++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/context.go b/context.go index be6262df..5ff2e73b 100644 --- a/context.go +++ b/context.go @@ -275,16 +275,16 @@ func (c *Context) BindWith(obj interface{}, b binding.Binding) error { } func (c *Context) ClientIP() string { - clientIP := c.Request.Header.Get("X-Real-IP") + clientIP := strings.TrimSpace(c.Request.Header.Get("X-Real-IP")) if len(clientIP) > 0 { return clientIP } clientIP = c.Request.Header.Get("X-Forwarded-For") - clientIP = strings.Split(clientIP, ",")[0] + clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0]) if len(clientIP) > 0 { - return strings.TrimSpace(clientIP) + return clientIP } - return c.Request.RemoteAddr + return strings.TrimSpace(c.Request.RemoteAddr) } func (c *Context) ContentType() string { diff --git a/context_test.go b/context_test.go index 7c9e0c7f..8898c3e1 100644 --- a/context_test.go +++ b/context_test.go @@ -401,15 +401,18 @@ func TestContextClientIP(t *testing.T) { c, _, _ := createTestContext() c.Request, _ = http.NewRequest("POST", "/", nil) - 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.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 " assert.Equal(t, c.ClientIP(), "10.10.10.10") + c.Request.Header.Del("X-Real-IP") assert.Equal(t, c.ClientIP(), "20.20.20.20") + c.Request.Header.Set("X-Forwarded-For", "30.30.30.30") assert.Equal(t, c.ClientIP(), "30.30.30.30") + c.Request.Header.Del("X-Forwarded-For") assert.Equal(t, c.ClientIP(), "40.40.40.40") }