#dotenv #env #environment #settings

macro dotenv_config

parse env to config struct for Rust

12 releases

0.2.1 Nov 1, 2024
0.2.0 Nov 1, 2024
0.1.9 Feb 7, 2024
0.1.8 Dec 26, 2023
0.1.3 Sep 11, 2022

#1028 in Configuration

Download history 872/week @ 2024-11-14 872/week @ 2024-11-21 931/week @ 2024-11-28 976/week @ 2024-12-05 1011/week @ 2024-12-12 1005/week @ 2024-12-19 998/week @ 2024-12-26 1608/week @ 2025-01-02 1629/week @ 2025-01-09 1419/week @ 2025-01-16 1480/week @ 2025-01-23 1198/week @ 2025-01-30 1245/week @ 2025-02-06 1817/week @ 2025-02-13 1745/week @ 2025-02-20 1434/week @ 2025-02-27

6,423 downloads per month
Used in mailinator-rs

MIT license

18KB
287 lines

Dot Env Config

use .env as config file and parse environments to config struct.

Usage

derive EnvConfig

use dotenv_config::EnvConfig;
use dotenvy::dotenv;

#[derive(Debug, PartialEq)]
enum Color {
    Red,
    Green,
    Blue,
}

impl std::str::FromStr for Color {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "red" => Ok(Color::Red),
            "green" => Ok(Color::Green),
            "blue" => Ok(Color::Blue),
            _ => Err("no match color"),
        }
    }
}

#[derive(Debug, EnvConfig)]
struct Config {
    #[env_config(default = "192.168.2.1")]
    server_addr: String,
    server_mode: bool,
    #[env_config(name = "ZINC_ENABLE", default = true)]
    enable: bool,
    #[env_config(name = "ZINC_NUMBER", default = 123456, help = "this is for demo")]
    num: Option<i64>,
    #[env_config(parse, default = "green")] // or parse=true
    color: Color,
}

fn main() {
    dotenv().ok();
    let cfg = Config::init().unwrap();
    println!("{:#?}", cfg);

    // print config help
    let help = Config::get_help();
    println!("{:#?}", help);
}

attribute env_config

you can use macro attribute set field attribute

  • name: change default environment key
  • default: if not set, used as default value

you can though system environments or .env file config it.

ZINC_ENABLE=false
ZINC_NUMBER=8787878

default load environment key is: structName_fieldName do UpperSnake, like above struct, default config key is:

CONFIG_SERVER_ADDR
CONFIG_SERVER_MODE
ZINC_ENABLE
ZINC_NUMBER

Dependencies

~1.8–2.6MB
~50K SLoC