serde-vars 0.3.1

Conveniently expose (environment) variables to your serde based data structures, like configurations.
Documentation

Serde Vars

Crates.io License Build Status docs.rs

Conveniently expose (environment) variables to your serde based data structures, like configurations.

{
    "redis": {
        "host": "127.0.0.1",
        "port": 6379,
        "username": "${REDIS_USERNAME}",
        "password": "${REDIS_PASSWORD}"
    }
}

The configuration file contains the variables, no need to decide on variable mappings at compile time.

#[derive(Debug, serde::Deserialize)]
struct Config {
    redis: Redis,
}

#[derive(Debug, serde::Deserialize)]
struct Redis {
    host: String,
    port: u16,
    username: String,
    password: String,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config_path = std::env::args()
        .nth(1)
        .unwrap_or_else(|| "config.json".to_owned());

    let config = std::fs::read_to_string(&config_path)?;
    
    let mut source = serde_vars::EnvSource::default();
    let mut de = serde_json::Deserializer::from_str(&config);
    let config: Config = serde_vars::deserialize(&mut de, &mut source)?;

    println!("{config:#?}");

    Ok(())
}