diff --git a/src/util/http.go b/src/util/http.go index 086fbab..a339822 100644 --- a/src/util/http.go +++ b/src/util/http.go @@ -1,6 +1,7 @@ package util import ( + "net" "net/http" "strings" ) @@ -23,21 +24,25 @@ func ipAddrFromRemoteAddr(s string) string { // requestGetRemoteAddress returns ip address of the client making the request, // taking into account http proxies -func requestGetRemoteAddress(r *http.Request) string { +func requestGetRemoteAddress(r *http.Request) net.IP { hdr := r.Header + hdrRealIP := hdr.Get("X-Real-Ip") hdrForwardedFor := hdr.Get("X-Forwarded-For") if hdrRealIP == "" && hdrForwardedFor == "" { - return ipAddrFromRemoteAddr(r.RemoteAddr) + return net.ParseIP(ipAddrFromRemoteAddr(r.RemoteAddr)) } + if hdrForwardedFor != "" { // X-Forwarded-For is potentially a list of addresses separated with "," parts := strings.Split(hdrForwardedFor, ",") + fwdIPs := make([]net.IP, len(parts)) for i, p := range parts { - parts[i] = strings.TrimSpace(p) + fwdIPs[i] = net.ParseIP(ipAddrFromRemoteAddr(strings.TrimSpace(p))) } - // TODO: should return first non-local address - return parts[0] + // return first address + return fwdIPs[0] } - return hdrRealIP + + return net.ParseIP(hdrRealIP) } diff --git a/src/util/log.go b/src/util/log.go index d7b6a0c..8a633f8 100644 --- a/src/util/log.go +++ b/src/util/log.go @@ -1,6 +1,7 @@ package util import ( + "net" "net/http" "os" "time" @@ -27,7 +28,7 @@ type HTTPReqInfo struct { // how long did it take to duration time.Duration // client IP Address - ipAddress string + ipAddress net.IP // client UserAgent userAgent string // referer header @@ -41,7 +42,7 @@ func logHTTPReqInfo(ri *HTTPReqInfo) { Int("code", ri.code). Int64("size", ri.size). Dur("duration", ri.duration). - Str("ipAddress", ri.ipAddress). + IPAddr("ipAddress", ri.ipAddress). Str("userAgent", ri.userAgent). Str("referer", ri.referer). Send()