Answer#
Keep settings out of the source: a file holds the normal values, and environment variables override them per machine (for example a port or a database URL set by the host). Deserialize the file into a struct so a wrong type is an error at start-up.
[dependencies]
serde = { version = "1", features = ["derive"] }
toml = "0.8"use serde::Deserialize;
use std::path::Path;
#[derive(Debug, Deserialize)]
struct Settings {
site_url: String,
#[serde(default = "default_port")]
port: u16,
database_url: Option<String>,
}
fn default_port() -> u16 {
8080
}
/// Order of precedence: environment variables win over the settings file, which wins over the defaults.
fn load(file: &Path, env: impl Fn(&str) -> Option<String>) -> Result<Settings, String> {
let text = std::fs::read_to_string(file).map_err(|e| format!("cannot read {}: {e}", file.display()))?;
let mut s: Settings = toml::from_str(&text).map_err(|e| format!("{} is not valid: {e}", file.display()))?;
if let Some(v) = env("SITE_URL") {
s.site_url = v;
}
if let Some(p) = env("PORT").and_then(|p| p.parse().ok()) {
s.port = p;
}
if let Some(v) = env("DATABASE_URL") {
s.database_url = Some(v);
}
Ok(s)
}
fn main() {
let dir = std::env::temp_dir().join("settings-demo");
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("settings.toml");
std::fs::write(&file, "site_url = \"https://example.test\"\n").unwrap();
println!("{:?}", load(&file, |_| None));
println!("{:?}", load(&file, |k| (k == "PORT").then(|| "9000".to_string())));
println!("{:?}", load(&dir.join("missing.toml"), |_| None).unwrap_err().contains("cannot read"));
std::fs::write(&file, "port = \"high\"\n").unwrap();
println!("{}", load(&file, |_| None).is_err());
}Ok(Settings { site_url: "https://example.test", port: 8080, database_url: None })
Ok(Settings { site_url: "https://example.test", port: 9000, database_url: None })
true
trueLine one uses the default port, line two shows the environment overriding it, line three a missing file, and line four a file of the wrong shape (port as text, and site_url missing).
Common mistakes#
- Putting passwords in the file that is committed to Git. Keep secrets in environment variables or a file outside the repository.
- Silently ignoring a bad value. Print which setting was rejected.
- Reading environment variables all over the program. Read them once, at start-up, into the struct.
Related questions#
Why not use JSON for settings?#
JSON has no comments, which settings files need. TOML or a similar format is easier to maintain by hand.
Is there a crate that does the layering for me?#
Yes, crates such as config and figment layer files and environment variables; the code above shows what they do, with no extra dependency.
Sources#
- toml crate: https://docs.rs/toml/
- serde field attributes: https://serde.rs/field-attrs.html