Crates.io | serde-vars |
lib.rs | serde-vars |
version | 0.2.0 |
created_at | 2025-05-18 14:29:53.268558+00 |
updated_at | 2025-05-19 19:07:17.078972+00 |
description | Conveniently expose (environment) variables to your serde based data structures, like configurations. |
homepage | |
repository | https://github.com/Dav1dde/serde-vars |
max_upload_size | |
id | 1678672 |
size | 78,484 |
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(())
}