use crate::proxy::Country;
use maxminddb::Reader;
use std::net::IpAddr;
use std::path::Path;
pub struct GeoDb {
reader: Reader<Vec<u8>>,
}
impl GeoDb {
#[cfg(feature = "geo-bundled")]
pub fn bundled() -> Result<Self, maxminddb::MaxMindDbError> {
const DB: &[u8] = include_bytes!("../data/dbip-country-lite.mmdb");
Ok(GeoDb {
reader: Reader::from_source(DB.to_vec())?,
})
}
pub fn open(path: impl AsRef<Path>) -> Result<Self, maxminddb::MaxMindDbError> {
let bytes = std::fs::read(path).map_err(maxminddb::MaxMindDbError::from)?;
Ok(GeoDb {
reader: Reader::from_source(bytes)?,
})
}
pub fn lookup(&self, ip: IpAddr) -> Option<Country> {
let rec: maxminddb::geoip2::Country = self.reader.lookup(ip).ok()?.decode().ok()??;
let country = rec.country;
let code = country.iso_code?;
Some(Country {
code: code.to_owned(),
name: country.names.english.unwrap_or(code).to_owned(),
})
}
}
#[cfg(all(test, feature = "geo-bundled"))]
mod tests {
use super::*;
#[test]
fn bundled_db_resolves_known_ips() {
let db = GeoDb::bundled().unwrap();
assert_eq!(db.lookup("8.8.8.8".parse().unwrap()).unwrap().code, "US");
assert_eq!(db.lookup("1.1.1.1".parse().unwrap()).unwrap().code, "AU");
assert!(!db
.lookup("8.8.8.8".parse().unwrap())
.unwrap()
.name
.is_empty());
}
}