config-rs icon indicating copy to clipboard operation
config-rs copied to clipboard

using Environment source to get List of struct

Open Gaelik-git opened this issue 1 year ago • 2 comments

Hello I would like to know if it's actually possible to have this Settings::new return a Ok result

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

#[derive(Debug, Deserialize)]
#[allow(unused)]
struct Auth {
    token: String,
    secret: String,
}

#[derive(Debug, Deserialize)]
#[allow(unused)]
pub struct Settings {
    auths: Vec<Auth>,
}

impl Settings {
    pub fn new() -> Result<Self, ConfigError> {
        let s = Config::builder()
            .add_source(
                Environment::with_prefix("APP")
                    .separator("_")
                    .try_parsing(true),
            )
            .build()?;

        s.try_deserialize()
    }
}

fn main() {
    let settings = Settings::new();

    // Print out our settings
    println!("{:?}", settings);
}

I was thinking something like APP_AUTHS_0_TOKEN=token APP_AUTHS_0_SECRET=secret cargo run I found the list_separator method on Environment but I think it's only to manage Vec<String>

Is it something that is currently possible ? If not is it a feature that would make sense to implement or maybe I should use another Source ?

Thanks

Gaelik-git avatar Feb 23 '24 08:02 Gaelik-git

Hi, I think something like that is not possible right now.

matthiasbeyer avatar Feb 23 '24 09:02 matthiasbeyer

It would be great to have support for this. Also, the convention that the OP has used is employed in ASP.Net as well.

momvart avatar Sep 04 '24 20:09 momvart