Skip to main content

Geo-IP API at the edge

Retrieve GeoIp (based on Maxmind) information at the edge to enrich or control the request

Compute

Use this solution in your CDB Edge Compute service:

use proxy_wasm::traits::*;
use proxy_wasm::types::*;


proxy_wasm::main! {{
    proxy_wasm::set_log_level(LogLevel::Trace);
    proxy_wasm::set_root_context(|_| -> Box<dyn RootContext> { Box::new(HttpHeadersRoot) });
}}

struct HttpHeadersRoot;

impl Context for HttpHeadersRoot {}

impl RootContext for HttpHeadersRoot {
    fn create_http_context(&self, _context_id: u32) -> Option<Box<dyn HttpContext>> {
        Some(Box::new(HttpHeaders {}))
    }

    fn get_type(&self) -> Option<ContextType> {
        Some(ContextType::HttpContext)
    }
}

struct HttpHeaders {}

impl Context for HttpHeaders {}

const INTERNAL_SERVER_ERROR: u32 = 500;

impl HttpContext for HttpHeaders {
    fn on_http_request_headers(&mut self, _: usize, _: bool) -> Action {
        let Some(country) = self.get_property(vec!["request.country"]) else {
            self.send_http_response(
                INTERNAL_SERVER_ERROR,
                vec![],
                Some(b"Malformed request - no country field"),
            );
            println!("Malformed request - no country field");
            return Action::Pause;
        };
        let Ok(country) = std::str::from_utf8(&country) else {
            self.send_http_response(
                INTERNAL_SERVER_ERROR,
                vec![],
                Some(b"Malformed request - country not utf8 string"),
            );
            println!("Malformed request - country not utf8 string");
            return Action::Pause;
        };
        println!("{}", country);

        let Some(city) = self.get_property(vec!["request.city"]) else {
            self.send_http_response(
                INTERNAL_SERVER_ERROR,
                vec![],
                Some(b"Malformed request - no city field"),
            );
            println!("Malformed request - no city field");
            return Action::Pause;
        };
        let Ok(city) = std::str::from_utf8(&city) else {
            self.send_http_response(
                INTERNAL_SERVER_ERROR,
                vec![],
                Some(b"Malformed request - city not utf8 string"),
            );
            println!("Malformed request - city not utf8 string");
            return Action::Pause;
        };
        println!("{}", city);
        Action::Continue
    }
}
[package]
name = "geoip"
version = "1.0.0"
edition = "2021"
authors = ["John Doe <john.doe@orange.com>"]
description = "Proxy-Wasm example: Retrieve geoIp information"


[lib]
crate-type = ["cdylib"]

[dependencies]
fastedge = { git ="https://github.com/G-Core/FastEdgeSDK.git", version = "0.1.10", features = ["json"]}
proxy-wasm = "0.2"