Skip to content

Instantly share code, notes, and snippets.

@simonkuhn

simonkuhn/geo.vcl

Last active Jul 24, 2020
Embed
What would you like to do?
Fastly VCL for geoip json output
sub vcl_recv {
#FASTLY recv
# We don't do other methods
if (req.method != "GET") {
return(error);
}
# Handle IPv4 or IPv6 provided in url path (nothing extraneous allowed, perform basic matching)
if (req.url.path ~ "^/([a-f0-9:.]+)$") {
set client.geo.ip_override = re.group.1;
# Use X-Forwarded-For if it exists (first IP is client)
} elseif (req.http.X-Forwarded-For) {
set client.geo.ip_override = regsub(req.http.X-Forwarded-For, ",.+$", "");
}
error 601;
return(lookup);
}
sub vcl_hash {
#FASTLY hash
set req.hash += req.http.host;
set req.hash += req.url;
set req.hash += client.ip;
return(hash);
}
sub vcl_hit {
#FASTLY hit
return(deliver);
}
sub vcl_miss {
#FASTLY miss
return(fetch);
}
sub vcl_pass {
#FASTLY pass
return(pass);
}
sub vcl_fetch {
#FASTLY fetch
return(deliver);
}
sub vcl_error {
#FASTLY error
# Assemble JSON output
synthetic {"{
"ip": ""} if(client.geo.ip_override, client.geo.ip_override, client.ip) {"",
"as": {
"name": ""} json.escape(client.as.name) {"",
"number": "} json.escape(client.as.number) {"
},
"client": {
"conn_speed": ""} json.escape( if(client.geo.conn_speed != "?", client.geo.conn_speed, "") ) {"",
"conn_type": ""} json.escape( if(client.geo.conn_type != "?", client.geo.conn_type, "") ) {"",
"proxy_desc": ""} json.escape( if(client.geo.proxy_description != "?", client.geo.proxy_description, "") ) {"",
"proxy_type": ""} json.escape( if(client.geo.proxy_type != "?", client.geo.proxy_type, "") ) {""
},
"geo": {
"area_code": "} json.escape(client.geo.area_code) {",
"city": ""} json.escape( if(client.geo.city.utf8 != "?", client.geo.city.utf8, "") ) {"",
"continent_code": ""} json.escape( if(client.geo.continent_code != "?", client.geo.continent_code, "") ) {"",
"country_code": ""} json.escape( if(client.geo.country_code != "?", client.geo.country_code, "") ) {"",
"country_code3": ""} json.escape( if(client.geo.country_code3 != "?", client.geo.country_code3, "") ) {"",
"country_name": ""} json.escape( if(client.geo.country_name.utf8 != "?", client.geo.country_name.utf8, "") ) {"",
"latitude": "} json.escape(client.geo.latitude) {",
"longitude": "} json.escape(client.geo.longitude) {",
"metro_code": "} json.escape(client.geo.metro_code) {",
"postal_code": ""} json.escape( if(client.geo.postal_code != "?", client.geo.postal_code, "") ) {"",
"region": ""} json.escape( if(client.geo.region.utf8 != "?", client.geo.region.utf8, "") ) {""
},
"time": {
"utc_offset": "} json.escape(client.geo.utc_offset) {"
}
}"};
set obj.status = 200;
set obj.response = "OK";
set obj.http.Content-Type = "application/json";
return (deliver);
}
sub vcl_deliver {
#FASTLY deliver
return(deliver);
}
sub vcl_log {
#FASTLY log
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.