Skip to content

Commit bfbe689

Browse files
committed
improve requestGetRemoteAddress utility
1 parent 66a035b commit bfbe689

2 files changed

Lines changed: 14 additions & 8 deletions

File tree

src/util/http.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package util
22

33
import (
4+
"net"
45
"net/http"
56
"strings"
67
)
@@ -23,21 +24,25 @@ func ipAddrFromRemoteAddr(s string) string {
2324

2425
// requestGetRemoteAddress returns ip address of the client making the request,
2526
// taking into account http proxies
26-
func requestGetRemoteAddress(r *http.Request) string {
27+
func requestGetRemoteAddress(r *http.Request) net.IP {
2728
hdr := r.Header
29+
2830
hdrRealIP := hdr.Get("X-Real-Ip")
2931
hdrForwardedFor := hdr.Get("X-Forwarded-For")
3032
if hdrRealIP == "" && hdrForwardedFor == "" {
31-
return ipAddrFromRemoteAddr(r.RemoteAddr)
33+
return net.ParseIP(ipAddrFromRemoteAddr(r.RemoteAddr))
3234
}
35+
3336
if hdrForwardedFor != "" {
3437
// X-Forwarded-For is potentially a list of addresses separated with ","
3538
parts := strings.Split(hdrForwardedFor, ",")
39+
fwdIPs := make([]net.IP, len(parts))
3640
for i, p := range parts {
37-
parts[i] = strings.TrimSpace(p)
41+
fwdIPs[i] = net.ParseIP(ipAddrFromRemoteAddr(strings.TrimSpace(p)))
3842
}
39-
// TODO: should return first non-local address
40-
return parts[0]
43+
// return first address
44+
return fwdIPs[0]
4145
}
42-
return hdrRealIP
46+
47+
return net.ParseIP(hdrRealIP)
4348
}

src/util/log.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package util
22

33
import (
4+
"net"
45
"net/http"
56
"os"
67
"time"
@@ -27,7 +28,7 @@ type HTTPReqInfo struct {
2728
// how long did it take to
2829
duration time.Duration
2930
// client IP Address
30-
ipAddress string
31+
ipAddress net.IP
3132
// client UserAgent
3233
userAgent string
3334
// referer header
@@ -41,7 +42,7 @@ func logHTTPReqInfo(ri *HTTPReqInfo) {
4142
Int("code", ri.code).
4243
Int64("size", ri.size).
4344
Dur("duration", ri.duration).
44-
Str("ipAddress", ri.ipAddress).
45+
IPAddr("ipAddress", ri.ipAddress).
4546
Str("userAgent", ri.userAgent).
4647
Str("referer", ri.referer).
4748
Send()

0 commit comments

Comments
 (0)