serde-vars

Crates.ioserde-vars
lib.rsserde-vars
version0.2.0
created_at2025-05-18 14:29:53.268558+00
updated_at2025-05-19 19:07:17.078972+00
descriptionConveniently expose (environment) variables to your serde based data structures, like configurations.
homepage
repositoryhttps://github.com/Dav1dde/serde-vars
max_upload_size
id1678672
size78,484
David Herberth (Dav1dde)

documentation

README

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(())
}
Commit count: 5

cargo fmt