Crates.io | envfig |
lib.rs | envfig |
version | 0.1.0 |
created_at | 2025-05-21 11:39:01.0555+00 |
updated_at | 2025-05-21 11:39:01.0555+00 |
description | A flexible and type-safe system for defining, documenting, and validating environment variables. |
homepage | |
repository | https://github.com/Mr-Leshiy/envfig |
max_upload_size | |
id | 1683315 |
size | 35,699 |
A flexible and type-safe system for defining, documenting, and validating environment variables.
The EnvVarDef
type provides a builder-style interface to define environment
variables with optional default values, human-friendly metadata (title, description,
example), and custom validation logic.
It supports loading required or optional variables using EnvVarDef::load
and
EnvVarDef::load_option
, and will return rich error types when parsing or
validation fails.
use std::{env, str::FromStr};
use envfig::{EnvVarDef, LoadError, validator::Validator};
// A simple validator that ensures the value is greater than zero
struct Positive;
impl Validator<i32> for Positive {
type Err = String;
fn validate(
self,
val: i32,
) -> Result<i32, Self::Err> {
if val > 0 {
Ok(val)
} else {
Err("Value must be positive".into())
}
}
}
// Set an environment variable
unsafe {
env::set_var("APP_PORT", "8080");
}
let port = EnvVarDef::new("APP_PORT")
.with_title("Application Port")
.with_description("The port the application listens on")
.with_example(8080)
.with_validator(Positive)
.load()
.unwrap();
Validator
trait.LoadError
.Validator<T>
is required to perform validation of environment variable values.