2019年的一个小更新 - 现在有一个比 BurntSushi/toml 更好的替代品,API更丰富,可用于处理 .toml 文件:
pelletier/go-toml (以及文档)
例如,有一个config.toml
文件(或者在内存中):
[postgres]
user = "pelletier"
password = "mypassword"
除了常规的将整个内容解组和编组成预定义结构(您可以在被接受的答案中看到)之外,使用
pelletier/go-toml,您还可以像这样查询单个值:
config, err := toml.LoadFile("config.toml")
if err != nil {
fmt.Println("Error ", err.Error())
} else {
directUser := config.Get("postgres.user").(string)
directPassword := config.Get("postgres.password").(string)
fmt.Println("User is", directUser, " and password is", directPassword)
configTree := config.Get("postgres").(*toml.Tree)
user := configTree.Get("user").(string)
password := configTree.Get("password").(string)
fmt.Println("User is", user, " and password is", password)
fmt.Printf("User position: %v\n", configTree.GetPosition("user"))
fmt.Printf("Password position: %v\n", configTree.GetPosition("password"))
q, _ := query.Compile("$..[user,password]")
results := q.Execute(config)
for ii, item := range results.Values() {
fmt.Println("Query result %d: %v", ii, item)
}
}
更新
还有spf13/viper,它可以使用.toml配置文件(以及其他支持的格式),但在许多情况下可能有些过度。
更新2
Viper并不是一个真正的替代方案(感谢@GoForth)。