1 unstable release

new 0.1.3 Feb 16, 2025
0.1.2 Feb 16, 2025
0.1.1 Feb 16, 2025
0.1.0 Feb 16, 2025

#255 in Configuration

MIT license

8KB
93 lines

mr_env

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_dotenv = "0.1.3"

Quick Start

use mr_dotenv::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_dotenv::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

License

MIT License

Contributing

Pull requests are welcome! Feel free to:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -am 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Dependencies

~205–640KB
~15K SLoC