Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Typed-env: describe the requirements of environment variables in a type-safe and ergonomic way
The story behind typed-env is that I'm sharing the environment variable requirements for both server and client side in my application. LazyLock
-like access is convenient in this case, because it helps us get rid of the duplicate environment loading logics in both application's main function. Besides, parsing booleans and lists from environment variables should follow some conventions, usually we accept DEBUG=1
or DEBUG=on
and reject DEBUG=<random str>
.
Example:
use typed_env::{Envar, EnvarDef};
// Define typed environment variables
static PORT: Envar<u16> = Envar::on_demand("PORT", || EnvarDef::Default(8080));
static DEBUG: Envar<bool> = Envar::on_demand("DEBUG", || EnvarDef::Default(false));
static DATABASE_URL: Envar<String> = Envar::on_demand("DATABASE_URL", || EnvarDef::Unset);
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Use the values - they're parsed automatically
let port = PORT.value()?; // u16
let debug = DEBUG.value()?; // bool
let db_url = DATABASE_URL.value()?; // String
println!("Server running on port {} (debug: {})", port, debug);
println!("Database: {}", db_url);
Ok(())
}
Although you can wrap figment's semi-hierarchical configuration with a LazyLock
to achieve the same functionality, simplicity is also a thing to a project that does not involve heavy configuration.
P.S: I've used Rust for a while and this is my first crate published to crates.io. I also use this project to get how to setup minimal GitHub actions for a rust project.
1 post - 1 participant
🏷️ rust_feed