Skip to main content

Module config_binding

Module config_binding 

Source
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 annotationEnv var absentEnv var present
#[config(env = "KEY", default = "v")]use "v"parse to field type
#[config(env = "KEY")] (non-Option)Errparse 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§

FromEnvStr
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 to default when the variable is absent.