处理Go程序的配置参数的首选方法是什么(在其他上下文中可能使用属性文件或ini文件的那种东西)?
当前回答
Viper是一个golang配置管理系统,可以使用JSON、YAML和TOML。看起来很有趣。
其他回答
https://github.com/spf13/viper和https://github.com/zpatrick/go-config是非常好的配置文件库。
看看贡菲
// 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)
另一种选择是使用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
}
Viper是一个golang配置管理系统,可以使用JSON、YAML和TOML。看起来很有趣。
像本文一样使用toml读取配置文件