chore(go): make country output more verbose

This commit is contained in:
Guanran Wang 2024-10-19 17:05:54 +08:00
parent 8ad7222bfb
commit 56f5b6db59
Signed by: nyancat
GPG key ID: 91F97D9ED12639CF

31
main.go
View file

@ -59,7 +59,22 @@ Disallow: /harm/to/self
}
func getIPCountry(ip string) string {
parsedIP := net.ParseIP(ip)
if parsedIP.IsPrivate() {
return "private IP"
}
if parsedIP.IsLoopback() {
return "loopback IP"
}
if parsedIP == nil {
log.Printf("Invalid IP address: %s", ip)
return "invalid IP"
}
if config.countrydb == "" {
log.Printf("Country database not set. Returning 'unknown'")
return "unknown"
}
@ -67,14 +82,19 @@ func getIPCountry(ip string) string {
return country.(string)
}
record, err := db.Country(net.ParseIP(ip))
record, err := db.Country(parsedIP)
if err != nil {
log.Print(err)
return "an error occurred"
log.Printf("GeoIP lookup failed for IP: %s, error: %v", ip, err)
return "GeoIP lookup failed"
}
country := record.Country.Names["en"]
ipCache.Store(ip, country) // Cache the result
country, ok := record.Country.Names["en"]
if !ok {
log.Printf("Country name not found in GeoIP data for IP: %s", ip)
return "unknown"
}
ipCache.Store(ip, country)
return country
}
@ -100,6 +120,7 @@ func handleRequest(w http.ResponseWriter, r *http.Request) {
if isHeadless {
fmt.Fprintf(w, "%s\n", sourceIP)
return
} else {
csp := []string{
"default-src 'none'",