作为标题,我想知道如何使用golang的toml文件.
在此之前,我展示了我的toml示例.这样对吗?
[datatitle]
enable = true
userids = [
"12345", "67890"
]
[datatitle.12345]
prop1 = 30
prop2 = 10
[datatitle.67890]
prop1 = 30
prop2 = 10
Run Code Online (Sandbox Code Playgroud)
然后,我想将这些数据设置为struct的类型.
因此,我想访问子元素,如下所示.
datatitle["12345"].prop1
datatitle["67890"].prop2
Run Code Online (Sandbox Code Playgroud)
提前致谢!
首先得到BurntSushi的toml解析器:
go get github.com/BurntSushi/toml
BurntSushi解析toml并将其映射到结构,这就是你想要的.
然后执行以下示例并从中学习:
package main
import (
"github.com/BurntSushi/toml"
"log"
)
var tomlData = `title = "config"
[feature1]
enable = true
userids = [
"12345", "67890"
]
[feature2]
enable = false`
type feature1 struct {
Enable bool
Userids []string
}
type feature2 struct {
Enable bool
}
type tomlConfig struct {
Title string
F1 feature1 `toml:"feature1"`
F2 feature2 `toml:"feature2"`
}
func main() {
var conf tomlConfig
if _, err := toml.Decode(tomlData, &conf); err != nil {
log.Fatal(err)
}
log.Printf("title: %s", conf.Title)
log.Printf("Feature 1: %#v", conf.F1)
log.Printf("Feature 2: %#v", conf.F2)
}
Run Code Online (Sandbox Code Playgroud)
注意它tomlData
以及它如何映射到tomlConfig
结构.
请访问https://github.com/BurntSushi/toml查看更多示例
2019 年的一个小更新 - 现在有BurntSushi/toml的更新替代品,具有更丰富的 API 来处理.toml文件:
例如有config.toml
文件(或在内存中):
[postgres]
user = "pelletier"
password = "mypassword"
Run Code Online (Sandbox Code Playgroud)
除了使用pelletier/go-toml将整个事物常规编组和解编为预定义结构(您可以在接受的答案中看到)之外,您还可以查询单个值,如下所示:
config, err := toml.LoadFile("config.toml")
if err != nil {
fmt.Println("Error ", err.Error())
} else {
// retrieve data directly
directUser := config.Get("postgres.user").(string)
directPassword := config.Get("postgres.password").(string)
fmt.Println("User is", directUser, " and password is", directPassword)
// or using an intermediate object
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)
// show where elements are in the file
fmt.Printf("User position: %v\n", configTree.GetPosition("user"))
fmt.Printf("Password position: %v\n", configTree.GetPosition("password"))
// use a query to gather elements without walking the tree
q, _ := query.Compile("$..[user,password]")
results := q.Execute(config)
for ii, item := range results.Values() {
fmt.Println("Query result %d: %v", ii, item)
}
}
Run Code Online (Sandbox Code Playgroud)
更新
还有spf13/viper可以与 .toml 配置文件(以及其他受支持的格式)一起使用,但在许多情况下它可能有点过大。
更新2
Viper 并不是真正的替代方案(归功于@GoForth)。