typed-env
Describe the requirements of environment variables in a type-safe and ergonomic way.
Features
- Type Safety: Parse environment variables directly into Rust types
- Flexible Loading: Choose between on-demand and startup loading strategies
- Globals:
LazyLock
-like globals for easy access to environment variables. - Rich Types: Support for primitives, booleans, strings, lists and your custom types.
- Default Values: Support for factory-based fallback/default values.
- Error Handling: Comprehensive error types with helpful messages
- Specialized Support:
- List: Parse comma-separated (or custom delimiter) lists with filtering options.
- Boolean: Flexible boolean parsing with multiple accepted formats:
true
,1
,yes
,y
,on
,enabled
(case insensitive) for true, andfalse
,0
,no
,n
,off
,disabled
(case insensitive) for false. - Custom Types: Parse custom types with custom parsing and error handling.
Quick Start
Add to your Cargo.toml
:
[]
= "0.1"
Basic Usage
use ;
// Define typed environment variables
static PORT: = on_demand;
static DEBUG: = on_demand;
static DATABASE_URL: = on_demand;
Loading Strategies
On-Demand Loading
Variables are parsed when first accessed and cached thereafter. If the environment variable is changed, the new value will be loaded on the next access.
static API_KEY: = on_demand;
// Parsed and cached on first call
let key1 = API_KEY.value?;
// Returns cached value
let key2 = API_KEY.value?;
// ...
unsafe
// ...
let key3 = API_KEY.value?; // Loads the new value
// ...
Startup Loading
Variables are parsed once at startup and never re-read:
static MAX_CONNECTIONS: = on_startup;
// Always returns the same value, even if env var changes
let max_conn = MAX_CONNECTIONS.value?;
WARNING: Envar::on_startup
does not load the environment variables at the actual startup time, but at the time of the first access.
Supported Types
Primitives
All standard integer and float types are supported:
static TIMEOUT_MS: = on_demand;
static RATE_LIMIT: = on_demand;
Booleans
Flexible boolean parsing with multiple accepted formats:
static ENABLE_LOGS: = on_demand;
Accepted values:
- True:
true
,1
,yes
,y
,on
,enabled
(case insensitive) - False:
false
,0
,no
,n
,off
,disabled
(case insensitive) - Empty string: treated as
false
Lists
Parse delimited lists with configurable separators and filtering:
use ;
// Define a custom list configuration
;
static ALLOWED_ORIGINS: =
on_demand;
// ALLOWED_ORIGINS="localhost,127.0.0.1,example.com"
let origins = ALLOWED_ORIGINS.value?;
for origin in origins.iter
Custom Types
use ;
// accept: LEVEL="vvv"
static LEVEL: = on_demand;
;
Default Values
Set Defaults
Provide a fallback value when the environment variable is not set:
static WORKER_THREADS: = on_demand;
// Returns 4 if WORKER_THREADS is not set
let threads = WORKER_THREADS.value?;
Unset (Required)
Require the environment variable to be present:
static SECRET_KEY: = on_demand;
// Returns Err(EnvarError::NotSet) if SECRET_KEY is not set
let secret = SECRET_KEY.value?;
Error Handling
The library provides detailed error information:
use EnvarError;
match DATABASE_URL.value
API Reference
Core Types
Envar<T>
: The main environment variable containerEnvarDef<T>
: Defines default behavior (Default(value)
orUnset
)ListEnvar<T, C>
: Container for list-type environment variablesListEnvarConfig
: Trait for configuring list parsing behavior
Methods
Envar::on_demand(name, default_factory)
: Create an on-demand loaded variableEnvar::on_startup(name, default_factory)
: Create a startup-loaded variableenvar.value()
: Get the parsed value, returnsResult<T, EnvarError>
envar.name()
: Get the environment variable name
Error Types
EnvarError::NotSet(name)
: Environment variable is not set and no default providedEnvarError::ParseError { varname, typename, value, reason }
: Failed to parse the valueEnvarError::TryDefault(varname)
: A "soft" error, indicating that the environment variable could fallback to the default value, if specified withEnvarDef::Default
.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.