macro envconfig_derive

Build a config structure from environment variables without boilerplate

12 releases (breaking)

0.11.0 Sep 7, 2024
0.10.0 Jun 8, 2021
0.9.1 Oct 9, 2020
0.8.0 Mar 31, 2020
0.5.0 Sep 25, 2018
Download history 33731/week @ 2024-07-28 31661/week @ 2024-08-04 38312/week @ 2024-08-11 46175/week @ 2024-08-18 57469/week @ 2024-08-25 43102/week @ 2024-09-01 46922/week @ 2024-09-08 45794/week @ 2024-09-15 47119/week @ 2024-09-22 64470/week @ 2024-09-29 32629/week @ 2024-10-06 56097/week @ 2024-10-13 49520/week @ 2024-10-20 54448/week @ 2024-10-27 41238/week @ 2024-11-03 86848/week @ 2024-11-10

233,167 downloads per month
Used in 19 crates (4 directly)

MIT license

19KB
220 lines

Envconfig logo

Build Status License Documentation

Initialize config structure from environment variables in Rust without boilerplate.

Stand With Ukraine

Install

[dependencies]
envconfig = "0.10.0"

Usage

Basic example

Let's say you application relies on the following environment variables:

  • DB_HOST
  • DB_PORT

And you want to initialize Config structure like this one:

struct Config {
    db_host: String,
    db_port: u16,
}

You can achieve this with the following code without boilerplate:

use envconfig::Envconfig;

#[derive(Envconfig)]
pub struct Config {
    #[envconfig(from = "DB_HOST")]
    pub db_host: String,

    #[envconfig(from = "DB_PORT", default = "5432")]
    pub db_port: u16,
}

fn main() {
    // Assuming the following environment variables are set
    std::env::set_var("DB_HOST", "127.0.0.1");

    // Initialize config from environment variables or terminate the process.
    let config = Config::init_from_env().unwrap();

    assert_eq!(config.db_host, "127.0.0.1");
    assert_eq!(config.db_port, 5432);
}

Nested configs

Configs can be nested. Just add #[envconfig(nested)] to nested field.

#[derive(Envconfig)]
pub struct DbConfig {
    #[envconfig(from = "DB_HOST")]
    pub host: String,

    #[envconfig(from = "DB_PORT", default = "5432")]
    pub port: u16,
}

#[derive(Envconfig)]
pub struct Config {
    #[envconfig(nested)]     // <---
    db: DbConfig,

    #[envconfig(from = "HOSTNAME")]
    hostname: String,
}

Custom types

Under the hood envconfig relies on FromStr trait. If you want to use a custom type as a field for config, you have to implement FromStr trait for your custom type.

Let's say we want to extend DbConfig with driver field, which is DbDriver enum that represents either Postgresql or Mysql:

pub enum DbDriver {
    Postgresql,
    Mysql,
}

impl std::str::FromStr for DbDriver {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_ref() {
            "postgres" => Ok(DbDriver::Postgresql),
            "mysql" => Ok(DbDriver::Mysql),
            _ => Err(format!("Unknown DB driver: {s}"))
        }
    }
}

#[derive(Envconfig)]
pub struct DbConfig {
    // ...
    #[envconfig(from = "DB_DRIVER")]
    pub driver: DbDriver,
}

If this seems too cumbersome, consider using other crates like strum to derive FromStr automatically.

use strum::EnumString;

#[derive(EnumString)]
pub enum DbDriver {
    Postgresql,
    Mysql,
}

Testing

When writing tests you should avoid using environment variables. Cargo runs Rust tests in parallel by default which means you can end up with race conditions in your tests if two or more are fighting over an environment variable.

To solve this you can initialise your struct from a HashMap<String, String> in your tests. The HashMap should match what you expect the real environment variables to be; for example DB_HOST environment variable becomes a DB_HOST key in your HashMap.

use envconfig::Envconfig;

#[derive(Envconfig)]
pub struct Config {
    #[envconfig(from = "DB_HOST")]
    pub db_host: String,

    #[envconfig(from = "DB_PORT", default = "5432")]
    pub db_port: u16,
}

#[test]
fn test_config_can_be_loaded_from_hashmap() {
    // Create a HashMap that looks like your environment
    let mut hashmap = HashMap::new();
    hashmap.insert("DB_HOST".to_string(), "127.0.0.1".to_string());

    // Initialize config from a HashMap to avoid test race conditions
    let config = Config::init_from_hashmap(&hashmap).unwrap();

    assert_eq!(config.db_host, "127.0.0.1");
    assert_eq!(config.db_port, 5432);
}

Contributing

Running tests

Tests do some manipulation with environment variables, so to prevent flaky tests they have to be executed in a single thread:

cargo test -- --test-threads=1

License

MIT © Sergey Potapov

Contributors

  • greyblake Potapov Sergey - creator, maintainer.
  • allevo Tommaso Allevi - support nested structures
  • hobofan Maximilian Goisser - update dependencies

Dependencies

~250–700KB
~17K SLoC