diff --git a/main.go b/main.go index 109b571..ba2a97e 100644 --- a/main.go +++ b/main.go @@ -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'",