Rust environment config with defaults and validation
Rust
use std::env;
#[derive(Debug)]
struct Config {
host: String,
port: u16,
debug: bool,
}
fn load() -> Result<Config, String> {
let host = env::var("APP_HOST").unwrap_or_else(|_| "127.0.0.1".into());
let port = env::var("APP_PORT")
.unwrap_or_else(|_| "8080".into())
.parse::<u16>()
.map_err(|e| format!("APP_PORT: {e}"))?;
let debug = env::var("APP_DEBUG").map(|v| v == "1" || v == "true").unwrap_or(false);
if port == 0 {
return Err("APP_PORT must be between 1 and 65535".into());
}
Ok(Config { host, port, debug })
}