处理Go程序的配置参数的首选方法是什么(在其他上下文中可能使用属性文件或ini文件的那种东西)?
当前回答
像本文一样使用toml读取配置文件
其他回答
看看贡菲
// load
config, _ := gonfig.FromJson(myJsonFile)
// read with defaults
host, _ := config.GetString("service/host", "localhost")
port, _ := config.GetInt("service/port", 80)
test, _ := config.GetBool("service/testing", false)
rate, _ := config.GetFloat("service/rate", 0.0)
// parse section into target structure
config.GetAs("service/template", &template)
Viper是一个golang配置管理系统,可以使用JSON、YAML和TOML。看起来很有趣。
对于更复杂的数据结构,我通常使用JSON。缺点是,您很容易以一堆代码来告诉用户错误在哪里、各种边缘情况和其他情况。
对于基本配置(api密钥,端口号,…)我在使用gcfg包时运气非常好。它基于git配置格式。
从文档中可以看到:
示例配置:
; Comment line
[section]
name = value # Another comment
flag # implicit value for bool is true
结构:
type Config struct {
Section struct {
Name string
Flag bool
}
}
读取它所需的代码:
var cfg Config
err := gcfg.ReadFileInto(&cfg, "myconfig.gcfg")
它还支持切片值,因此您可以允许多次指定一个键和其他类似的好特性。
我同意尼莫,我写了一个小工具,让这一切都很容易。
Bitbucket.org/gotamer/cfg是一个json配置包
将应用程序中的配置项定义为结构。 在第一次运行时保存struct中的json配置文件模板 您可以保存对配置的运行时修改
看医生。举个例子
另一种选择是使用TOML,这是Tom Preston-Werner创建的一种类似ini的格式。我为它构建了一个经过广泛测试的Go解析器。您可以像这里建议的其他选项一样使用它。例如,如果您在something.toml中有这个TOML数据
Age = 198
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z
然后你可以把它加载到你的Go程序中
type Config struct {
Age int
Cats []string
Pi float64
Perfection []int
DOB time.Time
}
var conf Config
if _, err := toml.DecodeFile("something.toml", &conf); err != nil {
// handle error
}