MoonBit 原生配置库:一处声明,多来源汇入。
import {
"MuVirus/moonfig/core" @config,
"MuVirus/moonfig/core/format/json_format" @jsonfmt,
}别名显式写出来。 省略别名时 MoonBit 按目录名绑定,核心会变成 @core,实测能编译; 本项目统一写 @config / @jsonfmt,短,且目录再调整时用户的写法不用跟着改。
using @config { type Config, type StringSource }
using @jsonfmt { type JsonFormat }
let cfg = Config::new()
.add(StringSource::new("{\"db\":{\"host\":\"localhost\",\"port\":5432}}", JsonFormat::new()))
.add(StringSource::new("{\"db\":{\"port\":6543}}", JsonFormat::new()))
.build()
cfg.get_string("db.host") // "localhost" ← 第一个来源提供,未被覆盖
cfg.get_int("db.port") // 6543 ← 第二个来源覆盖using @config {type Config, type StringSource}
using @jsonfmt {type JsonFormat, extract_from}
let cfg = Config::new()
.add(StringSource::new("{\"db\":{\"port\":\"5432\"}}", JsonFormat::new()))
.build()
cfg.get_string("db.port") // "5432"
cfg.get_int("db.port") // 报错:配置项 db.port 类型不符:期望 Int,实际 Str
struct TextPort {
port : String
} derive(FromJson)
struct NumericPort {
port : Int
} derive(FromJson)
let text : TextPort = extract_from(cfg, "db") // port = "5432"
let numeric : NumericPort = extract_from(cfg, "db") // 报错:期望数字,实际字符串using @config {type Config, type MemorySource, type Value}
let cfg = Config::new()
.add(
MemorySource::new(
Value::table({
"db": Value::table({ "host": Value::str("localhost"), "port": Value::int(5432L) }),
"debug": Value::bool(false),
"ratio": Value::float(0.5),
}),
),
)
.build()
cfg.get_string("db.host") // "localhost"
cfg.get_int("db.port") // 5432
cfg.get_bool("debug") // false
cfg.get_float("ratio") // 0.5using @config {type Config, type StringSource}
using @jsonfmt {type JsonFormat}
using @inifmt {type IniFormat}
using @dotenvfmt {type DotenvFormat}
let cfg = Config::new()
.add(StringSource::new("{\"db\":{\"host\":\"localhost\",\"port\":5432}}", JsonFormat::new())) // 默认值
.add(StringSource::new("[db]\nport = 6000\n", IniFormat::new())) // 配置文件
.add(StringSource::new("db.port=6543", DotenvFormat::new())) // 环境覆盖
.build()
cfg.get_string("db.host") // "localhost" 只有第一个来源提供
cfg.get_int("db.port") // 6543 最后加入的赢import {
"MuVirus/moonfig/file_source" @file_source,
"MuVirus/moonfig/env_source" @env_source,
"MuVirus/moonfig/cli_source" @cli_source,
}using @config {type Config, type MemorySource, type Value}
using @jsonfmt {type JsonFormat}
using @file_source {type FileSource}
using @env_source {type EnvSource}
using @cli_source {type CliSource}
let cfg = Config::new()
.add(MemorySource::new(Value::table({ "db": Value::table({ "port": Value::int(5432L) }) })))
.add(FileSource::new("config/app.json", JsonFormat::new())) // 读文件,格式自己挑
.add(EnvSource::new("APP_")) // APP_DB_PORT=6543 → db.port
.add(CliSource::new()) // --log-level=debug → log.level
.build()using @config {type Config, type MemorySource, type Value}
let cfg = Config::new()
.add(
MemorySource::new(
Value::table({ "db": Value::table({ "port": Value::int(5432L) }) }),
),
)
.build()
let origin = cfg.origin_of("db.port").unwrap()
origin.kind() // SourceKind::Memory
origin.label() // "memory"
origin.path().to_string() // "db.port"
cfg.origins() // [Origin { ... }],只列叶子路径using @jsonfmt {extract_from}
struct DbCfg {
host : String
port : Int
} derive(FromJson)
let db : DbCfg = extract_from(cfg, "db")using @jsonfmt {extract_from, Int64Text}
struct OrderCfg {
id : Int64Text
} derive(FromJson)
let order : OrderCfg = extract_from(cfg, "order")
order.id.to_int64() // 9007199254740993,超出 Double 精确范围也不丢using @config {type Rule}
cfg.validate([
Rule::int_range("db.port", 1L, 65535L),
Rule::one_of("log.level", ["debug", "info", "warn", "error"]),
Rule::allowed_keys("db", ["host", "port"]),
])using @jsonfmt {extract_validated_from}
impl @config.Validate for DbCfg with fn validate(self, prefix) {
@config.check_int_range(prefix.add("port"), self.port.to_int64(), 1L, 65535L)
}
let db : DbCfg = extract_validated_from(cfg, "db")try {
cfg.get_int("db.host")
} catch {
e => println(e)
}| 状态 | 方向 | 条目 |
|---|---|---|
| 🚧 | 核心 | 统一的配置值类型、按键合并、按键取值、按结构体取值、错误处理 |
| 🚧 | 多格式 | JSON、INI、dotenv、YAML、TOML、XML、CBOR 七种格式 |
| ✅ | 外部来源 | 配置文件、环境变量、命令行、多个来源任意组合 |
| 🚧 | 来源追踪 | 某个键最终来自哪一层 |
| ✅ | 校验 | 必填项、取值范围、自定义规则 |
| ⬜ | 自动发现格式 | 按后缀判断、按内容判断、无法判断时报错 |
| ⬜ | 热更新 | 监听文件变化、重新读取并合并、回调通知、失败时保留旧配置 |
Install
Download zipMoonBit 原生配置库:一处声明,多来源汇入。