Crates.io | nb-from-env |
lib.rs | nb-from-env |
version | 0.2.1 |
source | src |
created_at | 2023-09-24 03:23:48.600221 |
updated_at | 2023-10-20 23:58:58.305118 |
description | A convenient way to construct structrual configuration from environment variables |
homepage | |
repository | https://github.com/wangjun861205/from-env-rs |
max_upload_size | |
id | 981688 |
size | 14,659 |
This is a helper library which is dedicated to make extracting value from environment variables easy.
add below line to cargo.toml which is in your project
nb-from-env = "*"
use nb_from_env::{FromEnv, FromEnvDerive}
#[derive(FromEnvDerive)]
struct MyServerConfig {
log_level: Option<String>,
listen_address: String,
max_conns: i32,
is_debug: bool,
}
fn main() {
dotenv::dotenv().ok();
let config = MyServerConfig::from_env();
...
}
almost all of primitive types in rust are supported, include:
you can also implement FromEnv
for your type
If not specified, all environment variables name is the upper-case of field name:
#[derive(FromEnvDerive)]
struct MyConfig {
my_var: String // this will search for MY_VAR in environment varialbes
}
but you can use #[env_var]
tag to specify which environment variable is related to the field:
#[derive(FromEnvDerive)]
struct MyConfig {
#[env_var(THE_REAL_NAME)] // this will search for THE_REAL_NAME in environment variables
my_var: String
}
You can specify default value for non-existing environment variable by #[env_default]
tag:
struct MyConfig {
#[env_default("my default value")] // if MY_VAR not exists, "my default value" will assign to my_var
my_var: String
}
note that, the type of default value must be string, value will be convert to correspond type in from_env
function
When environment variable whic you expected does not exist, from_env
will panic if correspond field is not optional(i.e Option<T>
). Optional field will be None
if environment variable is not exists