config_rw

Crates.ioconfig_rw
lib.rsconfig_rw
version2.0.0
created_at2025-07-08 07:04:30.70592+00
updated_at2025-07-12 07:00:29.941556+00
description配置文件读取与写入
homepage
repository
max_upload_size
id1742150
size95,157
GuoYu (guoyucode)

documentation

README

Config RW - Multi-Instance Configuration Management Library

多实例配置管理库 - 支持多个配置文件的线程安全配置管理

🚀 Features | 特性

Multi-Instance Configuration | 多实例配置支持
Support multiple configuration file instances simultaneously
同时支持多个配置文件实例

Thread-Safe Global Access | 线程安全的全局访问
Use LazyLock for safe concurrent access across modules
使用 LazyLock 实现跨模块的安全并发访问

Priority-Based Configuration | 基于优先级的配置
Command line arguments > Configuration files > Environment variables
命令行参数 > 配置文件 > 环境变量

Type-Safe Configuration Access | 类型安全的配置访问
Built-in support for string, integer, float, boolean, and complex JSON types
内置支持字符串、整数、浮点数、布尔值和复杂 JSON 类型

Auto-Save and Hot Reload | 自动保存和热重载
Configuration changes are automatically saved to files
配置更改自动保存到文件中

Source Protection | 来源保护
Prevent accidental overwriting of command line and environment variables
防止意外覆盖命令行参数和环境变量

📦 Installation | 安装

Add this to your Cargo.toml:
将以下内容添加到你的 Cargo.toml 文件中:

[dependencies]
config_rw = "1"

🎯 Quick Start | 快速开始

Multi-Instance Usage | 多实例使用

use std::sync::LazyLock;
use config_rw::ConfigState;

// Define multiple configuration instances
// 定义多个配置实例
static DB_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("database.toml")
});

static API_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("api.toml")
});

static LOG_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("logging.toml")
});

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Database configuration
    // 数据库配置
    DB_CONFIG.set_string("host", "localhost".to_string())?;
    DB_CONFIG.set_i64("port", 5432)?;
    DB_CONFIG.set_bool("enabled", true)?;
    
    // API configuration
    // API 配置
    API_CONFIG.set_string("endpoint", "https://api.example.com".to_string())?;
    API_CONFIG.set_string("key", "your-api-key".to_string())?;
    API_CONFIG.set_i64("timeout", 30)?;
    
    // Logging configuration
    // 日志配置
    LOG_CONFIG.set_string("level", "info".to_string())?;
    LOG_CONFIG.set_string("file", "app.log".to_string())?;
    LOG_CONFIG.set_bool("console", true)?;
    
    // Read configuration values
    // 读取配置值
    let db_host = DB_CONFIG.get_string("host").unwrap_or_default();
    let api_endpoint = API_CONFIG.get_string("endpoint").unwrap_or_default();
    let log_level = LOG_CONFIG.get_string("level").unwrap_or_default();
    
    println!("Database host: {}", db_host);
    println!("API endpoint: {}", api_endpoint);
    println!("Log level: {}", log_level);
    
    Ok(())
}

🌟 Advanced Examples | 高级示例

1. Modular Configuration | 模块化配置

Separate configurations by functionality
按功能分离配置

use std::sync::LazyLock;
use config_rw::ConfigState;

// Database module configuration
// 数据库模块配置
static DB_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("database.toml")
});

// Cache module configuration
// 缓存模块配置
static CACHE_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("cache.toml")
});

// Security module configuration
// 安全模块配置
static SECURITY_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("security.toml")
});

mod database {
    use super::DB_CONFIG;
    
    pub fn connect() -> Result<(), Box<dyn std::error::Error>> {
        let host = DB_CONFIG.get_string("host").unwrap_or_default();
        let port = DB_CONFIG.get_i64("port").unwrap_or(5432);
        let ssl = DB_CONFIG.get_bool("ssl").unwrap_or(false);
        
        println!("Connecting to database: {}:{} (SSL: {})", host, port, ssl);
        println!("连接到数据库: {}:{} (SSL: {})", host, port, ssl);
        Ok(())
    }
}

mod cache {
    use super::CACHE_CONFIG;
    
    pub fn initialize() -> Result<(), Box<dyn std::error::Error>> {
        let redis_url = CACHE_CONFIG.get_string("redis.url").unwrap_or_default();
        let max_connections = CACHE_CONFIG.get_i64("redis.max_connections").unwrap_or(10);
        
        println!("Initializing cache: {} (max connections: {})", redis_url, max_connections);
        println!("初始化缓存: {} (最大连接数: {})", redis_url, max_connections);
        Ok(())
    }
}

mod security {
    use super::SECURITY_CONFIG;
    
    pub fn setup_auth() -> Result<(), Box<dyn std::error::Error>> {
        let jwt_secret = SECURITY_CONFIG.get_string("jwt.secret").unwrap_or_default();
        let token_expiry = SECURITY_CONFIG.get_i64("jwt.expiry_hours").unwrap_or(24);
        
        println!("Setting up authentication (token expiry: {}h)", token_expiry);
        println!("设置身份验证 (令牌过期时间: {}小时)", token_expiry);
        Ok(())
    }
}

2. Environment-Specific Configuration | 环境特定配置

Different configurations for different environments
不同环境使用不同配置

use std::sync::LazyLock;
use config_rw::ConfigState;

// Development environment
// 开发环境
static DEV_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("config.dev.toml")
});

// Production environment
// 生产环境
static PROD_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("config.prod.toml")
});

// Test environment
// 测试环境
static TEST_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("config.test.toml")
});

fn get_current_config() -> &'static LazyLock<ConfigState> {
    match std::env::var("ENVIRONMENT").unwrap_or_default().as_str() {
        "production" => &PROD_CONFIG,
        "test" => &TEST_CONFIG,
        _ => &DEV_CONFIG,
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = get_current_config();
    
    let database_url = config.get_string("database.url").unwrap_or_default();
    let debug_mode = config.get_bool("app.debug").unwrap_or(false);
    let log_level = config.get_string("logging.level").unwrap_or_default();
    
    println!("Environment: {}", std::env::var("ENVIRONMENT").unwrap_or("development".to_string()));
    println!("Database URL: {}", database_url);
    println!("Debug mode: {}", debug_mode);
    println!("Log level: {}", log_level);
    
    Ok(())
}

3. Complex Data Types | 复杂数据类型

Handle nested configurations and complex data structures
处理嵌套配置和复杂数据结构

use std::sync::LazyLock;
use config_rw::ConfigState;

static APP_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("app.toml")
});

fn setup_complex_config() -> Result<(), Box<dyn std::error::Error>> {
    // Set nested configuration
    // 设置嵌套配置
    APP_CONFIG.set_string("app.features.auth", "enabled".to_string())?;
    APP_CONFIG.set_bool("app.features.cache", true)?;
    APP_CONFIG.set_f64("app.performance.cache_size_mb", 256.0)?;
    
    // Set server configuration
    // 设置服务器配置
    APP_CONFIG.set_string("server.host", "0.0.0.0".to_string())?;
    APP_CONFIG.set_i64("server.port", 8080)?;
    APP_CONFIG.set_i64("server.max_connections", 1000)?;
    
    // Set database pool configuration
    // 设置数据库连接池配置
    APP_CONFIG.set_string("database.pool.url", "postgresql://localhost/mydb".to_string())?;
    APP_CONFIG.set_i64("database.pool.max_size", 10)?;
    APP_CONFIG.set_i64("database.pool.min_idle", 2)?;
    
    // Read nested configuration
    // 读取嵌套配置
    let auth_enabled = APP_CONFIG.get_string("app.features.auth").unwrap_or_default();
    let cache_enabled = APP_CONFIG.get_bool("app.features.cache").unwrap_or(false);
    let cache_size = APP_CONFIG.get_f64("app.performance.cache_size_mb").unwrap_or(128.0);
    
    println!("Auth: {}, Cache: {} ({}MB)", auth_enabled, cache_enabled, cache_size);
    println!("认证: {}, 缓存: {} ({}MB)", auth_enabled, cache_enabled, cache_size);
    
    Ok(())
}

4. Configuration Priority Demo | 配置优先级演示

Command line arguments override configuration files
命令行参数覆盖配置文件

use std::sync::LazyLock;
use config_rw::ConfigState;

static CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("config.toml")
});

fn priority_demo() -> Result<(), Box<dyn std::error::Error>> {
    // Set default values in config file
    // 在配置文件中设置默认值
    CONFIG.set_string("database.host", "localhost".to_string())?;
    CONFIG.set_i64("database.port", 5432)?;
    
    // Command line arguments will override these values
    // 命令行参数将覆盖这些值
    // Run with: cargo run -- database.host=production.db database.port=5433
    // 运行命令: cargo run -- database.host=production.db database.port=5433
    
    let host = CONFIG.get_string("database.host").unwrap_or_default();
    let port = CONFIG.get_i64("database.port").unwrap_or(5432);
    
    println!("Database host: {}", host);
    println!("Database port: {}", port);
    println!("数据库主机: {}", host);
    println!("数据库端口: {}", port);
    
    Ok(())
}

📚 API Reference | API 参考

ConfigState Methods | ConfigState 方法

Reading Configuration | 读取配置

  • get_string(path: &str) -> Option<String> - Get string value | 获取字符串值
  • get_i64(path: &str) -> Option<i64> - Get integer value | 获取整数值
  • get_f64(path: &str) -> Option<f64> - Get float value | 获取浮点数值
  • get_bool(path: &str) -> Option<bool> - Get boolean value | 获取布尔值
  • get_value(path: &str) -> Value - Get raw JSON value | 获取原始JSON值

Writing Configuration | 写入配置

  • set_string(path: &str, value: String) -> Result<(), Error> - Set string value | 设置字符串值
  • set_i64(path: &str, value: i64) -> Result<(), Error> - Set integer value | 设置整数值
  • set_f64(path: &str, value: f64) -> Result<(), Error> - Set float value | 设置浮点数值
  • set_bool(path: &str, value: bool) -> Result<(), Error> - Set boolean value | 设置布尔值
  • set_value(path: &str, value: Value) -> Result<(), Error> - Set raw JSON value | 设置原始JSON值

Initialization | 初始化

  • init_config<P: AsRef<Path>>(config_path: P) -> Self - Initialize with config file | 使用配置文件初始化

🔧 Configuration File Format | 配置文件格式

Supports TOML format with nested structures:
支持带有嵌套结构的 TOML 格式:

[database]
host = "localhost"
port = 5432
enabled = true

[api]
endpoint = "https://api.example.com"
key = "your-api-key-here"
timeout = 30

[logging]
level = "info"
file = "app.log"
console = true

[app]
[app.features]
auth = "enabled"
cache = true

[app.performance]
cache_size_mb = 256.0
max_connections = 1000

🚀 Command Line Arguments | 命令行参数

Support various command line argument formats:
支持各种命令行参数格式:

# Key-value pairs
# 键值对
./program database.host=localhost database.port=5432

# Quoted values
# 带引号的值
./program app.name="My App" database.password="secret123"

# Boolean values
# 布尔值
./program app.debug=true logging.console=false

🌍 Environment Variables | 环境变量

Environment variables use uppercase with dots converted to underscores:
环境变量使用大写字母,点号转换为下划线:

# Linux/macOS
export DATABASE_HOST=localhost
export DATABASE_PORT=5432
export APP_DEBUG=true

# Windows PowerShell
$env:DATABASE_HOST="localhost"
$env:DATABASE_PORT="5432"
$env:APP_DEBUG="true"

💡 Best Practices | 最佳实践

1. Organize by Functionality | 按功能组织

// Good: Separate configs by domain
// 好:按域分离配置
static DB_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("database.toml")
});

static API_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("api.toml")
});

2. Use Meaningful Names | 使用有意义的名称

// Good: Descriptive names
// 好:描述性名称
static USER_SERVICE_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("user_service.toml")
});

// Avoid: Generic names
// 避免:通用名称
static CONFIG1: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("config1.toml")
});

3. Handle Errors Gracefully | 优雅地处理错误

fn safe_config_access() {
    let host = DB_CONFIG.get_string("host").unwrap_or_else(|| {
        eprintln!("Warning: Using default database host");
        "localhost".to_string()
    });
    
    let port = DB_CONFIG.get_i64("port").unwrap_or_else(|| {
        eprintln!("Warning: Using default database port");
        5432
    });
}

🔒 Thread Safety | 线程安全

The library is fully thread-safe using LazyLock:
该库使用 LazyLock 完全线程安全:

use std::sync::LazyLock;
use std::thread;
use config_rw::ConfigState;

static SHARED_CONFIG: LazyLock<ConfigState> = LazyLock::new(|| {
    ConfigState::init_config("shared.toml")
});

fn main() {
    let handles: Vec<_> = (0..10).map(|i| {
        thread::spawn(move || {
            // Safe concurrent access
            // 安全的并发访问
            let value = SHARED_CONFIG.get_string("app.name").unwrap_or_default();
            println!("Thread {}: {}", i, value);
        })
    }).collect();
    
    for handle in handles {
        handle.join().unwrap();
    }
}

📄 License | 许可证

This project is licensed under the MIT License - see the LICENSE file for details.
本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

🤝 Contributing | 贡献

Contributions are welcome! Please feel free to submit a Pull Request.
欢迎贡献!请随时提交 Pull Request。

📞 Support | 支持

If you have any questions or need help, please open an issue on GitHub.
如果您有任何问题或需要帮助,请在 GitHub 上提交 issue。

Commit count: 0

cargo fmt