【问题标题】:Why am I getting a "missing field" error using config-rs?为什么我会收到错误消息(缺少字段 `web3_node_provider`)?
【发布时间】:2022-12-06 10:11:49
【问题描述】:

我是 Rust 的新手——我很困惑为什么当我使用 config-rs 时出现 cargo run 错误。似乎在s.try_deserialize() 失败

配置.rs

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()
    }
}

主要.rs

mod settings;

use settings::Settings;

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

我几乎完全遵循 config-rs 中的层次结构示例,所以我确定我只是误解了一些基本的东西或遗漏了一些东西。我可以使用"Web3NodeProvider.url",但不能使用"web3_node_provider.ethereum_mainnet_node_url_http"

默认.toml

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

本地.toml

[Web3NodeProvider]
alchemy_api_key = "randomapikey"

【问题讨论】:

  • 如果不实际查看您的配置文件,很难说。它说“缺少字段”,所以您的配置文件很可能缺少该信息
  • @NikolayZakirov 我已经更新了我的问题。您认为这是因为我在 Toml 文件中缺少 web3_node_provder 吗?
  • 是的,我想是这样。
  • @NikolayZakirov 刚刚更新,但我已经尝试将它添加到 toml 文件中,但仍然出现相同的错误

标签: rust


【解决方案1】:

我认为您必须将配置中的字段命名为属性名称而不是类名称。像这样:

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

【讨论】:

  • 谢谢你——现在可以用了!我不确定我是否完全理解为什么会这样,但我很感谢你!
猜你喜欢
  • 2015-01-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多