Layered configuration from files and environment variables
cargo add philiprehberger-config-loaderLayered configuration from files and environment variables
[dependencies]
philiprehberger-config-loader = "0.2.0"
use philiprehberger_config_loader::{ConfigBuilder, ConfigValue};
let config = ConfigBuilder::new()
.default("port", 8080_i64)
.default("debug", false)
.add_file("config.toml")
.add_env_prefix("APP")
.set("version", "1.0.0")
.build()
.unwrap();
// Typed getters
let port = config.get_int("port"); // Some(8080)
let debug = config.get_bool("debug"); // Some(false)
let ver = config.get_string("version"); // Some("1.0.0")
# config.toml
host = "localhost"
port = 3000
debug = true
[database]
url = "postgres://localhost/mydb"
pool_size = 5
With prefix APP, environment variables map as follows:
| Environment Variable | Config Key |
|---|---|
APP_PORT | port |
APP_DATABASE__URL | database.url |
Double underscore (__) maps to dot-separated nesting.
Later layers override earlier ones:
| Type | Description |
|---|---|
ConfigBuilder | Builder for assembling configuration layers |
Config | Immutable configuration store |
ConfigValue | Enum: String, Integer, Float, Bool, Array |
ConfigError | Error: FileNotFound, ParseError, TypeError |
| Method | Description |
|---|---|
ConfigBuilder::new() | Create a new builder |
.default(key, value) | Set a default value |
.add_file(path) | Add a TOML file source (errors if missing) |
.add_file_optional(path) | Add a TOML file source, silently skipped if missing |
.add_env_prefix(prefix) | Add env var source with prefix |
.set(key, value) | Manual override (highest priority) |
.build() | Build the Config |
| Method | Description |
|---|---|
.get(key) | Get a &ConfigValue |
.get_string(key) | Get as &str |
.get_int(key) | Get as i64 |
.get_float(key) | Get as f64 |
.get_bool(key) | Get as bool |
.get_array(key) | Get as &[String] |
.keys() | Iterate over all keys |
cargo test
cargo clippy -- -D warnings
If you find this project useful: