aconfig
理由
关于GO中的配置加载有许多解决方案。我一直在寻找一个易于使用和尽可能易于理解的简单装载机。目标是从4个位置加载配置:默认值(在代码),文件,环境变量,命令行标志。该图书馆与所有这些来源一起使用。
特征
- 简单的API。
- 清洁和测试的代码。
- 自动字段映射。
- 支持不同的来源:
- 代码中的默认值
- 文件(JSON,YAML,TOML,DOTENV,HCL)
- 环境变量
- 命令行标志
- 无依赖项(文件解析器是可选的)。
- 能够走上配置字段的能力。
安装
GO版本1.14+
go get github.com/cristalhq/ aconfig
例子
aconfig .Config{
// feel free to skip some steps 🙂
// SkipDefaults: true,
// SkipFiles: true,
// SkipEnv: true,
// SkipFlags: true,
EnvPrefix: "APP",
FlagPrefix: "app",
Files: []string{"/var/opt/myapp/config.json", "ouch.yaml"},
FileDecoders: map[string] aconfig .FileDecoder{
// from ` aconfig yaml` submodule
// see submodules in repo for more formats
".yaml": aconfig yaml.New(),
},
})
// IMPORTANT: define your own flags with `flagSet`
flagSet := loader.Flags()
if err := loader.Load(); err != nil {
panic(err)
}
// configuration fields will be loaded from (in order):
//
// 1. defaults set in structure tags (see MyConfig defenition)
// 2. loaded from files `file.json` if not `ouch.yaml` will be used
// 3. from corresponding environment variables with the prefix `APP_`
// 4. command-line flags with the prefix `app.` if they are\”>
type MyConfig struct { Port int `default:\"1111\" usage:\"just give a number\"` Auth struct { User string `required:\"true\"` Pass string `required:\"true\"` } Pass string `default:\"\" env:\"SECRET\" flag:\"sec_ret\"` } var cfg MyConfig loader := aconfig . LoaderFor ( & cfg , aconfig . Config { // feel free to skip some steps :) // SkipDefaults: true, // SkipFiles: true, // SkipEnv: true, // SkipFlags: true, EnvPrefix : \"APP\" , FlagPrefix : \"app\" , Files : [] string { \"/var/opt/myapp/config.json\" , \"ouch.yaml\" }, FileDecoders : map [ string ] aconfig . FileDecoder { // from ` aconfig yaml` submodule // see submodules in repo for more formats \".yaml\" : aconfig yaml . New (), }, }) // IMPORTANT: define your own flags with `flagSet` flagSet := loader . Flags () if err := loader . Load (); err != nil { panic ( err ) } // configuration fields will be loaded from (in order): // // 1. defaults set in structure tags (see MyConfig defenition) // 2. loaded from files `file.json` if not `ouch.yaml` will be used // 3. from corresponding environment variables with the prefix `APP_` // 4. command-line flags with the prefix `app.` if they are
另请参见示例:示例_test.go。
与spf13/cobra游乐场集成。
文档
查看这些文档。
执照
麻省理工学院许可证。
