Expand description
Typed configuration binding — read environment variables into strongly-typed structs.
Use #[derive(Config)] (requires macros feature) to generate a load() method
that reads env vars and parses them into the annotated field types.
§Quick start
ⓘ
use rust_web_server::Config;
#[derive(rust_web_server::Config)]
#[config(prefix = "APP_")]
struct MyConfig {
#[config(env = "PORT", default = "8080")]
port: u16,
#[config(env = "DATABASE_URL")]
database_url: String, // required — Err if env var is absent
#[config(env = "FEATURE_FLAG")]
feature_flag: Option<bool>, // None if env var is absent or empty
}
// At startup:
let cfg = MyConfig::load().expect("failed to load config");
println!("listening on port {}", cfg.port);§Field derivation rules
| Field annotation | Env var absent | Env var present |
|---|---|---|
#[config(env = "KEY", default = "v")] | use "v" | parse to field type |
#[config(env = "KEY")] (non-Option) | Err | parse to field type |
#[config(env = "KEY")] (Option<T>) | Ok(None) | parse, wrap in Some |
No #[config] — uses PREFIX + SCREAMING_SNAKE_CASE(field) | same as non-Option rules |
§Supported types
All primitive Rust scalar types implement FromEnvStr and can be used as field types:
String, bool, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64,
i128, isize, f32, f64. Wrap in Option<T> for optional fields.
Traits§
- From
EnvStr - Parse a value from an environment variable string.
Functions§
- load_
optional - Read an optional env var and parse it into
Option<T>. - load_
required - Read a required env var and parse it into
T. - load_
with_ default - Read an env var and parse it into
T, falling back todefaultwhen the variable is absent.