作为标题,我想知道如何使用戈朗的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提前感谢!
发布于 2015-12-16 09:46:45
首先获取BurntSushi的toml解析器:
go get github.com/BurntSushi/toml
BurntSushi解析文档并将其映射到结构中,这正是您想要的。
然后执行以下示例并从中学习:
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结构。
发布于 2015-12-18 03:48:48
这个问题是用推荐的pkg /toml解决的!我做了下面的工作,这是代码的一部分。
toml实例
[title]
enable = true
[title.clientinfo.12345]
distance = 30
some_id = 6Golang实例
type TitleClientInfo struct {
Distance int `toml:"distance"`
SomeId int `toml:"some_id"`
}
type Config struct {
Enable bool `toml:"enable"`
ClientInfo map[string]TitleClientInfo `toml:"clientinfo"`
}
var config Config
_, err := toml.Decode(string(d), &config)然后,它就可以像我预期的那样使用了。
config.ClientInfo[12345].Distance谢谢!
发布于 2020-04-14 13:39:58
使用解决方案Viper,您可以使用JSON、TOML、YAML、HCL、INI和其他属性格式的配置文件。
创建文件:
./config.toml首次进口:
import (config "github.com/spf13/viper")初始化:
config.SetConfigName("config")
config.AddConfigPath(".")
err := config.ReadInConfig()
if err != nil {
log.Println("ERROR", err.Error())
}得到价值:
config.GetString("datatitle.12345.prop1")
config.Get("datatitle.12345.prop1").(int32)https://stackoverflow.com/questions/34307488
复制相似问题