#config #env #macro #configuration #environment

envconfig

Build a config structure from environment variables without boilerplate

11 releases (breaking)

0.9.1 Oct 9, 2020
0.8.0 Mar 31, 2020
0.6.0 Dec 22, 2019
0.5.1 Apr 16, 2019
0.5.0 Sep 25, 2018

#14 in Configuration

Download history 309/week @ 2020-07-04 384/week @ 2020-07-11 498/week @ 2020-07-18 525/week @ 2020-07-25 473/week @ 2020-08-01 708/week @ 2020-08-08 606/week @ 2020-08-15 452/week @ 2020-08-22 434/week @ 2020-08-29 370/week @ 2020-09-05 411/week @ 2020-09-12 321/week @ 2020-09-19 462/week @ 2020-09-26 720/week @ 2020-10-03 661/week @ 2020-10-10 604/week @ 2020-10-17

2,112 downloads per month
Used in 2 crates

MIT license

9KB
93 lines

Envconfig logo

Build Status License Documentation

Initialize config structure from environment variables in Rust without boilerplate.

Usage

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 {
    host: String,
    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);
}

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

~0.4–0.8MB
~21K SLoC