Admin Config
配置管理库,为 Rust Web 应用提供统一的配置加载和管理功能。
功能特性
- ✅ TOML 配置文件支持
- ✅ 环境变量覆盖
- ✅ 类型安全的配置结构
- ✅ 默认值支持
- ✅ 多数据库支持(MongoDB、MySQL、PostgreSQL、SQLite、Redis、Neo4j、Qdrant、SeekDB)
- ✅ 自动生成安全密钥
- ✅ 第三方服务配置(邮件、短信、对象存储)
- ✅ 配置文件自动查找
安装
添加依赖到 Cargo.toml:
[]
= "0.1"
快速开始
1. 生成配置文件
首先创建配置文件。你可以从 crate 包含的示例配置开始:
# 复制示例配置文件(位于 crate 根目录)
或者使用代码生成默认配置:
use AppConfig;
2. 使用配置
use ;
支持的数据库
- MongoDB - 文档数据库
- MySQL - 关系型数据库
- PostgreSQL - 关系型数据库
- SQLite - 嵌入式数据库
- Redis - 缓存数据库
- Neo4j - 图数据库
- Qdrant - 向量数据库
- SeekDB - 多模型数据库
配置优先级
支持三种配置方式,优先级从高到低:
- 环境变量(最高优先级)
- 简写格式:
PORT,REDIS_IP,MONGODB_USER - 层级格式:
SERVER__PORT,REDIS__HOST,DATABASE__MONGODB__USERNAME
- 简写格式:
- config.toml 配置文件
- 默认值(最低优先级)
配置文件示例
服务器配置
[]
= "actix-admin-server"
= 3400
= "0.0.0.0"
= "info"
数据库配置
[]
= "localhost"
= 27017
= "admin_db"
= "admin"
= "password"
= 10
= 10
[]
= "localhost"
= 3306
= "app_db"
= "root"
= "password"
= 10
= 10
[]
= "localhost"
= 5432
= "app_db"
= "postgres"
= "password"
= 10
= 10
[]
= "./data.db"
= 10
[]
= "localhost"
= 6333
= false
[]
= "localhost"
= 7687
= "neo4j"
= ""
= ""
= false
Redis 配置
[]
= "localhost"
= 6379
= ""
= 0
= 20
= 5
认证配置
[]
= "your-secret-key"
= 24
= 7
安全配置
[]
= "64-char-hex-string"
= "32-char-hex-string"
= "64-char-hex-string"
= "32-char-hex-string"
= true
= ""
= false
邮件服务配置
[]
= "smtp.gmail.com"
= 587
= ""
= ""
= "System"
= ""
= true
短信服务配置
[]
= "tencent"
= ""
= ""
= ""
= ""
对象存储配置
[]
= "tencent"
[]
= ""
= ""
= ""
= "ap-guangzhou"
[]
= "./uploads"
= "/uploads"
= true
完整的配置示例请参考 config.example.toml。
环境变量
支持通过环境变量覆盖配置项:
# 服务器
# MongoDB
# Redis
# 认证
辅助方法
use ;
let config = load?;
let mongo_url = config.database.mongodb.to_connection_url;
let mysql_url = config.database.mysql.to_connection_url;
let redis_url = config.redis.connection_string;
let token_ttl = config.auth.token_expiry_seconds;
let refresh_ttl = config.auth.refresh_token_expiry_seconds;
let allowed_origins = config.security.allowed_origins_list;
安全密钥生成
配置中的所有安全密钥使用 Rust 的加密安全随机数生成器(CSPRNG)自动生成:
use SecurityConfig;
let config = default;
assert_eq!;
assert_eq!;
config.validate?;
生成的密钥包括:
aes_key: 64位十六进制(32字节,AES-256)aes_iv: 32位十六进制(16字节)api_key_encrypt_key: 64位十六进制(32字节)password_salt: 32位十六进制(16字节)
生产环境建议
-
密钥管理
- 使用环境变量存储敏感信息
- 使用密钥管理服务(AWS Secrets Manager、HashiCorp Vault)
- 不要将真实密钥提交到 Git 仓库
- 不要在多个环境共享密钥
-
安全配置
- 定期更新密钥和密码
- 启用 HTTPS 和 Secure Cookie
- 设置适当的 CORS 策略
-
配置文件管理
- 将
config.toml添加到.gitignore - 使用
config.example.toml作为模板 - 使用不同的配置文件区分环境
- 将
API 文档
完整的 API 文档请访问 docs.rs/admin-config
示例
查看 config.example.toml 了解完整的配置示例。
贡献
欢迎提交 Issue 和 Pull Request!
许可
MIT License