首页 > 解决方案 > 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”键的国家/地区名称,如何从该结构及其对(语言代码,国家名称)中检索。

标签: rust

解决方案


你可以看看测试是如何编写的,它会让你知道如何提取你正在寻找的信息:

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));

推荐阅读