作为标题,我想知道如何使用golang的toml文件.
在此之前,我展示了我的toml示例.这样对吗?
[datatitle] enable = true userids = [ "12345", "67890" ] [datatitle.12345] prop1 = 30 prop2 = 10 [datatitle.67890] prop1 = 30 prop2 = 10
然后,我想将这些数据设置为struct的类型.
因此,我想访问子元素,如下所示.
datatitle["12345"].prop1 datatitle["67890"].prop2
提前致谢!
首先得到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) }
注意它tomlData
以及它如何映射到tomlConfig
结构.
请访问https://github.com/BurntSushi/toml查看更多示例