use std::net::IpAddr;
use std::path::PathBuf;
use coip_reader::Reader;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct CompactGeo {
country: Option<CountryInfo>,
location: Option<LocationInfo>,
}
#[derive(Debug, Deserialize)]
struct CountryInfo {
iso_code: Option<String>,
names: Option<LocalizedNames>,
}
#[derive(Debug, Deserialize)]
struct LocalizedNames {
en: Option<String>,
#[serde(rename = "zh-CN")]
zh_cn: Option<String>,
}
#[derive(Debug, Deserialize)]
struct LocationInfo {
latitude: Option<f64>,
longitude: Option<f64>,
time_zone: Option<String>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
let (coi_path, ip_str) = if args.len() >= 3 {
(PathBuf::from(&args[1]), args[2].as_str())
} else {
let default_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("test-vectors")
.join("minimal_dual_stack.coi");
(default_path, "8.8.8.8")
};
let reader = Reader::open(&coi_path)?;
reader.verify_checksums()?;
let ip: IpAddr = ip_str.parse()?;
println!(
"Opened {} ({} unique records)",
coi_path.display(),
reader.header().record_count
);
let full = reader.lookup_value(ip)?;
println!("Full lookup ({ip}): {full:#?}");
let proj = reader.compile_projection([
"country.iso_code",
"country.names.en",
"country.names.zh-CN",
"location.latitude",
"location.longitude",
"location.time_zone",
])?;
let typed: Option<CompactGeo> = reader.lookup_with_projection(ip, &proj)?;
if let Some(geo) = typed {
if let Some(country) = geo.country {
println!(
"Country: iso={:?}, en={:?}, zh-CN={:?}",
country.iso_code,
country.names.as_ref().and_then(|n| n.en.as_deref()),
country.names.as_ref().and_then(|n| n.zh_cn.as_deref()),
);
}
if let Some(loc) = geo.location {
println!(
"Location: lat={:?}, lon={:?}, tz={:?}",
loc.latitude, loc.longitude, loc.time_zone
);
}
}
Ok(())
}