ClientIP() must trim the white spaces

This commit is contained in:
Manu Mtz-Almeida 2015-05-24 15:35:08 +02:00
parent 80d3cc6b75
commit 0a9030f9d7
2 changed files with 10 additions and 7 deletions

View File

@ -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 {

View File

@ -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")
}