3 releases

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

#530 in Configuration

32 downloads per month

MIT/Apache

8KB
83 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_env = "0.1.0"
dotenv = "0.15"

Quick Start

use mr_env::EnvConfig;

#[derive(EnvConfig, Debug)]
pub struct KafkaConfig {
    #[env(name = "KAFKA_BOOTSTRAP", required = true)]
    pub bootstrap: String,
    
    #[env(name = "KAFKA_TOPIC", required = true)]
    pub topic: String,
}

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

Create a .env file:

KAFKA_BOOTSTRAP=localhost:9092
KAFKA_TOPIC=my-topic

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)]
    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 kafka_config

# Database configuration
cargo run --example database_config

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

~220–660KB
~16K SLoC