1 unstable release

new 0.1.0 Feb 17, 2025

#362 in Configuration

Download history 74/week @ 2025-02-12

74 downloads per month

MIT license

7KB
84 lines

mr_env_plus

A lightweight Rust library for managing environment variables through derive macros. Easily load your configuration from environment variables and .env files with type safety.

Installation

Add this to your Cargo.toml:

[dependencies]
mr_env_plus = "0.1.0"

Quick Start

use mr_env_plus::EnvConfig;

#[derive(EnvConfig, Debug)]
pub struct Config {
    #[env(name = "APP_NAME", required = true)]
    pub app_name: String,

    #[env(name = "APP_PORT", default = "8080")]
    pub port: u16,

    #[env(name = "DEBUG_MODE", default = "false")]
    pub debug: bool,
}

fn main() {
  
   mr_env_plus::init().ok();

    let config = Config::from_env();
    println!("Config: {:?}", config);
}

Create a .env file:

APP_NAME=prod
APP_PORT=3000
DEBUG_MODE=false

Features

  • 🔧 Simple derive macro for environment variables
  • 📝 Automatic .env file loading
  • ✅ Required and optional fields
  • 🛡️ Type-safe configuration
  • ❌ Clear error messages

Usage Examples

Optional Fields

#[derive(EnvConfig, Debug)]
pub struct ServerConfig {
    #[env(name = "SERVER_HOST", required = true, default="127.0.0.1")]
    pub host: String,
  
    #[env(name = "SERVER_PORT", required = false)]
    pub port: u16,  // Will use default if not set
}

Different Types

#[derive(EnvConfig, Debug)]
pub struct DatabaseConfig {
    #[env(name = "DB_URL", required = true)]
    pub url: String,
  
    #[env(name = "DB_PORT", required = true)]
    pub port: u16,
  
    #[env(name = "DB_POOL_SIZE", required = false)]
    pub pool_size: u32,
  
    #[env(name = "DB_ENABLED", required = false)]
    pub enabled: bool,
}

Error Messages

The library provides clear error messages:

Error: Environment variable DB_URL is required
Error: Failed to parse DB_PORT: invalid digit found in string

Running Examples

Check out the included examples:

# Kafka configuration
cargo run --example simple

# Database configuration
cargo run --example with_path

Dependencies

~250–710KB
~17K SLoC