From 8ad7222bfb407ec74545b965e1249ec9e63ee78d Mon Sep 17 00:00:00 2001 From: Guanran Wang Date: Sat, 19 Oct 2024 16:46:50 +0800 Subject: [PATCH] fix(go): handle ipv6 addresses correctly --- main.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 9dc3a3f..109b571 100644 --- a/main.go +++ b/main.go @@ -80,10 +80,18 @@ func getIPCountry(ip string) string { func handleRequest(w http.ResponseWriter, r *http.Request) { sourceIP := func() string { - if ip := r.Header.Get("X-Forwarded-For"); ip != "" { + if ip := r.Header.Get("X-Forwarded-For"); ip != "" { return strings.Split(ip, ",")[0] } - return strings.Split(r.RemoteAddr, ":")[0] + + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + errorText := fmt.Sprintf("Unable to parse remote address: %v", err) + log.Printf(errorText) + return errorText + } + + return host }() isHeadless := strings.HasPrefix(r.Header.Get("User-Agent"), "curl/")