fix(go): handle ipv6 addresses correctly

This commit is contained in:
Guanran Wang 2024-10-19 16:46:50 +08:00
parent 265c998df0
commit 8ad7222bfb
Signed by: nyancat
GPG key ID: 91F97D9ED12639CF

12
main.go
View file

@ -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/")