Skip to content

Commit

Permalink
improve requestGetRemoteAddress utility
Browse files Browse the repository at this point in the history
  • Loading branch information
panz3r committed Jul 16, 2023
1 parent 66a035b commit bfbe689
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
17 changes: 11 additions & 6 deletions src/util/http.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package util

import (
"net"
"net/http"
"strings"
)
Expand All @@ -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)
}
5 changes: 3 additions & 2 deletions src/util/log.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package util

import (
"net"
"net/http"
"os"
"time"
Expand All @@ -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
Expand All @@ -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()
Expand Down

0 comments on commit bfbe689

Please sign in to comment.