tin-config-load 0.2.0

A simple Rust library for loading configuration from files and environment variables
Documentation
  • Coverage
  • 40%
    2 out of 5 items documented0 out of 0 items with examples
  • Size
  • Source code size: 26.8 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 263.9 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 10s Average build duration of successful builds.
  • all releases: 19s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • Repository
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • JiabinTang

tin-config-load

基于 config 的轻量 Rust 配置加载库,从文件与环境变量分层加载配置。

用法

默认加载可选文件 ./config/default(扩展名自动探测,支持 TOML/JSON/YAML 等格式)与 APP_ 前缀的环境变量:

use serde::Deserialize;
use tin_config_load::ConfigLoader;

#[derive(Deserialize)]
struct Config {
    host: String,
    port: u16,
}

fn main() -> Result<(), tin_config_load::ConfigError> {
    let cfg: Config = ConfigLoader::default()
        .file("config/local")            // 必选文件,缺失时报错
        .optional_file("config/secret")  // 可选文件,缺失时忽略
        .env("MY_APP")                   // 追加环境变量前缀
        .build()?;
    println!("{}:{}", cfg.host, cfg.port);
    Ok(())
}

优先级

  • 文件 source 按注册顺序加载,后注册的覆盖先注册的;
  • 环境变量 source 始终在文件之后加载,因此环境变量恒覆盖文件,与 file/env 的调用顺序无关;
  • 环境变量之间同样按注册顺序,后注册的覆盖先注册的。

ConfigLoader::default() 等价于:

ConfigLoader::empty()
    .optional_file("./config/default")
    .env("APP")

需要完全自定义默认路径与前缀时,从 ConfigLoader::empty() 开始装配即可。

错误处理

build() 返回自有错误类型 ConfigError,区分两类失败:

  • ConfigError::Build:读取或解析配置源失败,例如必选文件不存在;
  • ConfigError::Deserialize:配置构建成功,但无法反序列化为目标类型。

注意事项

  • 相对路径基于进程当前工作目录(CWD)解析,需要稳定定位时请使用绝对路径;
  • 文件扩展名可省略(自动探测),也可传完整路径(如 config/local.toml)。

License

MIT