rust 为什么使用config-rs时会出现“缺少字段”错误?

ykejflvf  于 2023-01-13  发布在  其他
关注(0)|答案(1)|浏览(145)

我很困惑为什么我在使用config-rs执行cargo run时会收到Err(missing field "web3_node_provider")错误。似乎在s.try_deserialize()时失败:

use config::{Config, ConfigError, Environment, File};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[allow(unused)]
struct Web3NodeProvider {
    ethereum_mainnet_node_url_http: String,
    alchemy_api_key: String,
}

#[derive(Debug, Deserialize)]
#[allow(unused)]
pub struct Settings {
    web3_node_provider: Web3NodeProvider,
}

impl Settings {
    pub fn new() -> Result<Self, ConfigError> {
        let s = Config::builder()
            .add_source(File::with_name("config/default"))
            .add_source(File::with_name("config/local").required(false))
            .add_source(Environment::with_prefix("app"))
            .build()?;
        s.try_deserialize()
    }
}

fn main() {
    let settings = Settings::new();
    println!("{:?}", settings);
}

我在config-rs中基本上遵循了hierarchy example,所以我确信我只是误解了一些基本的东西或者遗漏了一些东西,我可以使用"Web3NodeProvider.url",但不能使用"web3_node_provider.ethereum_mainnet_node_url_http"
default.toml

[Web3NodeProvider]
ethereum_mainnet_node_url_http = "https://eth-mainnet.g.alchemy.com/v2/"
alchemy_api_key = "alchemy-api-key"

local.toml

[Web3NodeProvider]
alchemy_api_key = "randomapikey"
1rhkuytd

1rhkuytd1#

根据example,你必须在config中将你的字段命名为属性名而不是结构名(类型),如下所示:

[web3_node_provider]
ethereum_mainnet_node_url_http = "https://eth-mainnet.g.alchemy.com/v2/"
alchemy_api_key = "alchemy-api-key"

相关问题