#env #variables #env-var #environment #extract #extractor #required

env-extractor

Modules to extract environment variables

7 releases

0.0.7 Sep 20, 2020
0.0.6 Sep 10, 2020
0.0.5 Aug 29, 2020

#35 in #required

21 downloads per month

MIT/Apache

8KB
151 lines

env-extractor

Usage

Basic example to extract an environment variable as String :

use env_extractor::{env_var, required};

fn load_path() -> required::Result<String> {
    env_var("PATH").as_required()
}

Another example to use custom type :

fn load_my_path() -> required::Result<MyPath> {
    // Note that this is exactly the same as load_path()
    env_var("PATH").as_required()
}

How to convert is represented using built-in std::str::FromStr :

struct MyPath {
    inner: String,
}
impl FromStr for MyPath {
    type Err = <String as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(MyPath {
            inner: s.to_string(),
        })
    }
}

Of course, required::Result can tell us the key when it's not present (std::env::VarError cannot).

match load_my_path() {
    Ok(path) => println!("path: {}", path.inner),
    Err(NotPresent(key)) => println!("not present: {}", key),
    Err(e) => println!("unexpected error: {:?}", e),
}

Use as_optional() instead when handling optional value :

let sample: Option<MyPath> = env_var("foooooo").as_optional()?;

No runtime deps