rust - maxminddb-rust,获取特定语言的国家/地区值
问题描述
我决定开始学习 Rust,我还没有完成他们的书,但我正在尝试构建和运行其他项目,以便我可以从源代码中学习。我现在对 maxmind-rust crate 感兴趣,特别是我想从 .mmdb 文件中检索国家、城市和 asn 值。
我尝试将 struct 转换maxmind::geoip2::Country
为字符串并使用 json crate,但导致了我无法自行修复的错误。
使用的代码:
use maxminddb::geoip2;
use std::net::IpAddr;
use std::str::FromStr;
fn main()
{
let mmdb_file = maxminddb::Reader::open("C:\\path\\to\\GeoLite2-City.mmdb").unwrap();
let ip_addr: IpAddr = FromStr::from_str("8.8.8.8").unwrap();
let geoip2_country: geoip2::Country = mmdb_file.lookup(ip_addr).unwrap();
println!("{:?}", geoip2_country);
}
输出是:
Country
{
continent: Some(Continent
{
code: Some("NA"),
geoname_id: Some(6255149),
names: Some(
{
"de": "Nordamerika",
"en": "North America",
"es": "Norteam?rica",
"fr": "Am?rique du Nord",
"ja": "?????",
"pt-BR": "Am?rica do Norte",
"ru": "???????? ???????",
"zh-CN": "???"
})
}),
country: Some(Country
{
geoname_id: Some(6252001),
iso_code: Some("US"),
names: Some(
{
"de": "USA",
"en": "United States",
"es": "Estados Unidos",
"fr": "?tats-Unis",
"ja": "???????",
"pt-BR": "Estados Unidos",
"ru": "???",
"zh-CN": "??"
})
}),
registered_country: Some(Country
{
geoname_id: Some(6252001),
iso_code: Some("US"),
names: Some(
{
"de": "USA",
"en": "United States",
"es": "Estados Unidos",
"fr": "?tats-Unis",
"ja": "???????",
"pt-BR": "Estados Unidos",
"ru": "???",
"zh-CN": "??"
})
}),
represented_country: None,
traits: None
}
这是 maxminddb::geoip2::Country 结构(http://oschwald.github.io/maxminddb-rust/maxminddb/geoip2/struct.Country.html)
将最后一行代码更改为
println!("{:?}", geoip2_country.country);
仅输出country
字段:
country: Some(Country
{
geoname_id: Some(6252001),
iso_code: Some("US"),
names: Some(
{
"de": "USA",
"en": "United States",
"es": "Estados Unidos",
"fr": "?tats-Unis",
"ja": "???????",
"pt-BR": "Estados Unidos",
"ru": "???",
"zh-CN": "??"
})
}),
但是看看 maxminddb::geoip2::model::Country 的结构(http://oschwald.github.io/maxminddb-rust/maxminddb/geoip2/model/struct.Country.html),我很困惑如果我想获取“en”键的国家/地区名称,如何从该结构及其对(语言代码,国家名称)中检索。
解决方案
你可以看看测试是如何编写的,它会让你知道如何提取你正在寻找的信息:
https://github.com/oschwald/maxminddb-rust/blob/master/src/maxminddb/reader_test.rs
(实际上,在查看测试后,我没有找到任何提取您要查找的内容的示例)
那应该返回您的期望:
let country_name = geoip2_country.country
.and_then(|cy| cy.names)
.and_then(|n| n.get("en")
.map(String::from));
推荐阅读
- ffmpeg - FFMPEG连接多个视频原因:太多不可见帧
- django - Django 尝试在不存在的文件夹中查找模板
- php - 在控制器中获取特定信息?
- ios - 未定义符号:_OBJC_CLASS_$_SKStoreReviewController 测试 Gamemaker Studio 2 项目时
- spring - “错误:无法找到或加载主类 ${start-class} spring boot
- python - 如何使用不同的var导入相同的文件
- amazon-dynamodb - 无法连接到本地 dynamodb 数据库
- amazon-web-services - Amazon Athena - 使用存储为字符串的数字查询列
- php - foreach 未执行 - 仅显示第一个变量输入
- sql-server - 通过 3 个参数在连接表中搜索的参数化存储过程条件连接