From 83381e49332a656f0c387ee0fd6a46117a7a5539 Mon Sep 17 00:00:00 2001 From: Lyle Mantooth Date: Sat, 20 May 2023 11:50:57 -0400 Subject: [PATCH] Use MaxMindDb and thiserror. --- .gitignore | 1 + Cargo.toml | 4 +++- src/lib.rs | 27 +++++++++++++++++++++------ 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index ea8c4bf..96ef6c0 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml index 6a519ea..6f39e57 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,11 @@ [package] name = "locat" -version = "0.2.0" +version = "0.3.0" edition = "2021" publish = ["menteeth"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +maxminddb = "0.23" +thiserror = "1" diff --git a/src/lib.rs b/src/lib.rs index d0f0d6a..e6c37a8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,17 +1,32 @@ use std::net::IpAddr; /// Allows geo-locating IPs and keeps analytics. -pub struct Locat {} +pub struct Locat { + geoip: maxminddb::Reader>, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("maxminddb error: {0}")] + MaxMindDb(#[from] maxminddb::MaxMindDBError), +} impl Locat { - pub fn new(_geoip_country_db_path: &str, _analytics_db_path: &str) -> Self { - // TODO: read geoip db, create analytics db - Self {} + pub fn new(geoip_country_db_path: &str, _analytics_db_path: &str) -> Result { + // Todo: create analytics db. + + Ok(Self { + geoip: maxminddb::Reader::open_readfile(geoip_country_db_path)?, + }) } /// Converts an address to an ISO 3166-1 alpha-2 country code. - pub fn ip_to_iso_code(&self, _addr: IpAddr) -> Option<&str> { - None + pub fn ip_to_iso_code(&self, addr: IpAddr) -> Option<&str> { + self.geoip + .lookup::(addr) + .ok()? + .country? + .iso_code } /// Returns a map of country codes to number of requests.