mirror of
https://github.com/darwincereska/envkit.git
synced 2026-06-11 10:23:23 -05:00
1.7 KiB
1.7 KiB
envkit
envkit is a small Rust crate for reading environment variables and converting them into typed values.
It keeps the API minimal:
EnvLoader::getreads a required variable.EnvLoader::get_orreads a variable with a fallback.EnvLoader::get_optreturnsOption<T>.with_prefixlets you build loaders for namespaced variables likeAPP_PORTorDB_HOST.
Supported types
envkit currently supports:
Stringbool- numeric types:
i8,i16,i32,i64,i128,isize,u8,u16,u32,u64,u128,usize,f32,f64
Boolean parsing accepts:
true/false1/0t/f
Quick start
use envkit::EnvLoader;
fn main() -> Result<(), envkit::error::EnvError> {
let loader = EnvLoader;
let port: u16 = loader.get("PORT")?;
let debug: bool = loader.get_or("DEBUG", false);
let app_name: String = loader.get_opt("APP_NAME").unwrap_or_else(|| "envkit".to_string());
println!("port={port}, debug={debug}, app_name={app_name}");
Ok(())
}
Prefixed variables
use envkit::EnvLoader;
fn main() -> Result<(), envkit::error::EnvError> {
let loader = EnvLoader;
let app = loader.with_prefix("APP_");
let host: String = app.get("HOST")?;
let port: u16 = app.get_or("PORT", 8080);
println!("host={host}, port={port}");
Ok(())
}
If you use the prefixed loader above, it reads APP_HOST and APP_PORT.
Errors
envkit returns EnvError for two cases:
MissingVarwhen the environment variable is not presentInvalidwhen parsing fails
Examples
See the examples/ folder for runnable usage samples.
Development
Run the test suite with:
cargo test