GCP HTTP/HTTPS Load Balancers offer great performance, and today I learned of a cool almost hidden feature: the ability to stamp custom headers with client GeoIP info. Here’s a Terraform config snippet:
resource "google_compute_backend_service" "MY_BACKEND_SERVICE" {
provider = google-beta
name = "my-backend-service"
health_checks = [ google_compute_health_check.MY_HEALTHCHECK.id ]
backed {
group = google_compute_instance_group.MY_INSTANCE_GROUP.self_link
balancing_mode = "UTILIZATION"
max_utilization = 1.0
}
custom_request_headers = [ "X-Client-Geo-Location: {client_region},{client_city}" ]
custom_response_headers = [ "X-Cache-Hit: {cdn_cache_status}" ]
}
This will cause the Backend Service to stamp all HTTP requests with a custom header called “X-Client-Geo-Location” with the country abbreviation and city. It can then be parsed on the server to get this information for the client without having to rely on messy X-Forwarded-For parsing and GeoIP lookups.
Here’s a Python example that redirects the user to UK or Australia localized websites:
#!/usr/bin/env python3
import os
try:
client_location = os.environ.get('HTTP_X_CLIENT_GEO_LOCATION', None)
if client_location:
[country,city] = client_location.split(',')
websites = { 'UK': "www.foo.co.uk", 'AU': "www.foo.au" }
if country in websites:
local_website = websites[country]
else:
local_website = "www.foo.com"
print("Status: 301\nLocation: https://{}\n".format(local_website))
except Exception as e:
print("Status: 500\nContent-Type: text/plain\n\n{}".format(e))