diff --git a/context.go b/context.go index be6262d..5ff2e73 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 7c9e0c7..8898c3e 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") }