Configuration

Environment variables

dotenvy-badge

dotenvy⮳ supersedes dotenv⮳.

use std::env;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    // Load environment variables from .env file.
    // Fails if .env file not found, not readable or invalid.
    dotenvy::dotenv()?;

    for (key, value) in env::vars() {
        println!("{key}: {value}");
    }

    Ok(())
}

To retrieve a single environment variable,

use std::env;

fn env_extract() -> String {
    let log_env_var = env::var("RUST_LOG").unwrap_or_else(|_| "debug".into());
    println!("RUST_LOG: {log_env_var}");

    let user_env_var = env::var("USER").expect("$USER is not set");
    println!("USER: {user_env_var}");

    // Inspect an environment variable at compile-time.
    // Uncomment to test.
    // let shell = env!("SHELL", "$SHELL is not set");

    let optional_value = option_env!("SHELL");

    optional_value.unwrap_or("no shell set").to_string()
}

fn main() {
    println!("SHELL: {}", env_extract());
}

Working with environment variables in Rust

Envy

envy-badge

Envy can deserialize environment variables into typesafe struct.

[dependencies]
envy = "0.4"
serde = { version = "1.0", features = ["derive"] }
#![allow(dead_code)]

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct Configuration {
    port: u16,
    items_per_page: u16,
}

fn main() {
    let c = envy::from_env::<Configuration>()
        .expect("Please provide PORT and ITEMS_PER_PAGE env vars");

    let c2 = envy::prefixed("MY_APP__")
        .from_env::<Configuration>()
        .expect(
            "Please provide MY_APP__PORT and MY_APP__ITEMS_PER_PAGE env vars",
        );

    println!("c: {:?} c2: {:?}", c, c2);
}

Config

config-badge

Config is a layered configuration system for Rust applications. It reads from JSON, TOML, YAML, INI, RON, JSON5 files.

Confy

confy-badge

use serde::Deserialize;
use serde::Serialize;

#[derive(Serialize, Deserialize)]
struct MyConfig {
    version: u8,
    api_key: String,
}

/// `MyConfig` implements `Default`
impl ::std::default::Default for MyConfig {
    fn default() -> Self {
        Self {
            version: 0,
            api_key: "".into(),
        }
    }
}

fn main() -> Result<(), confy::ConfyError> {
    let _cfg: MyConfig = confy::load("my-app-name", None)?;
    // confy::store("my-app-name", None, cfg)?;
    Ok(())
}

See also

dotenv-badge