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.
This commit is contained in:
Philipp Meinen 2015-07-25 20:39:05 +02:00
parent 704d690ac0
commit 6bf060f179
2 changed files with 11 additions and 1 deletions

View File

@ -8,6 +8,7 @@ import (
"errors" "errors"
"io" "io"
"math" "math"
"net"
"net/http" "net/http"
"strings" "strings"
"time" "time"
@ -291,7 +292,13 @@ func (c *Context) ClientIP() string {
return clientIP 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. // ContentType returns the Content-Type header of the request.

View File

@ -531,6 +531,9 @@ func TestContextClientIP(t *testing.T) {
c.Request.Header.Del("X-Forwarded-For") c.Request.Header.Del("X-Forwarded-For")
assert.Equal(t, c.ClientIP(), "40.40.40.40") 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) { func TestContextContentType(t *testing.T) {