Detecting Visitor Country
Identify the visitor's country using the IP geolocation API.
// Let's assume you have saved the API's JSON response to variable `response`
let response = {
// ... (other fields)
"locationData": {
"countryName": "United States",
"countryCode": "US",
// ... (other fields)
}
};
if (response.locationData.countryCode === "US") {
console.log("A United States visitor from one of the fifty contiguous states");
}
package main
import "fmt"
// Assuming you have made the API call and have the JSON response stored in a variable called `response`
var response = map[string]interface{}{
// ... (other fields)
"locationData": map[string]interface{}{
"countryName": "United States",
"countryCode": "US",
// ... (other fields)
},
}
func main() {
if response["locationData"].(map[string]interface{})["countryCode"] == "US" {
fmt.Println("A United States visitor from one of the fifty states")
}
}
# Fetch geolocation data
response = requests.get(url, headers=headers)
data = response.json()
if data['locationData']['countryCode'] == "US":
print("A United States visitor from one of the fifty states")
Filtering by Country Groups
Determine whether a visitor's country (using ISO 3166-1 alpha-2 codes) is in a list of countries of interest.
let response = {
"locationData": {
"countryCode": "US",
}
};
let fiveEyesCountries = ["US", "GB", "CA", "AU", "NZ"];
let isVisitorFromFiveEyes = fiveEyesCountries.includes(response.locationData.countryCode);
console.log("Is visitor from a 'Five Eyes' country?", isVisitorFromFiveEyes);
package main
import "fmt"
var response = map[string]map[string]string{
"locationData": {
"countryCode": "US",
},
}
var fiveEyesCountries = []string{"US", "GB", "CA", "AU", "NZ"}
func main() {
isVisitorFromFiveEyes := false
for _, country := range fiveEyesCountries {
if response["locationData"]["countryCode"] == country {
isVisitorFromFiveEyes = true
break
}
}
fmt.Println("Is visitor from a 'Five Eyes' country?", isVisitorFromFiveEyes)
}
# Countries group
countries_group = ["US", "DE", "JP", "CA", "AU"]
# Fetch geolocation data
response = requests.get(url, headers=headers)
data = response.json()
# Storing the results data
ip_address = data["ip"]
country_code = data["locationData"]["countryCode"]
if country_code in countries_group:
print(f"{ip_address} is from a specific country group. Country Code: {country_code}")
else:
print(f"{ip_address} is from a specific country group. Country Code: {country_code}")Updated 2 days ago
