英文:
Parsing a yaml file with Golang
问题
我正在尝试使用Golang解析一个yaml
文件。我定义了以下types
:
type DockerNetwork struct {
MyNetwork struct {
driver string
} `yaml:"my_network"`
}
// DockerNetworks represent the docker Networks type
type DockerNetworks struct {
networks []DockerNetwork
}
所以我已经准备好了单元测试:
func TestDockerNetwork(t *testing.T) {
dn := DockerNetworks{}
var data = `
networks:
my_network:
driver: bridge
`
err := yaml.Unmarshal([]byte(data), &dn)
if err != nil {
log.Fatalf("error: %v", err)
t.Error("Could not Unmarshal the data")
}
log.Println(fmt.Sprintf("--- t:\n%v\n\n", dn))
}
我期望它能正常工作,但是我得不到任何输出:
2016/12/14 13:38:12 --- t:
{{}}
我做错了什么?
英文:
I'm trying to parse a yaml
file with Golang. I defined the following types
:
type DockerNetwork struct {
MyNetwork struct {
driver string
} `yaml:"my_network"`
}
// DockerNetworks represent the docker Networks type
type DockerNetworks struct {
networks []DockerNetwork
}
so I have my unit test in place:
func TestDockerNetwork(t *testing.T) {
dn := DockerNetworks{}
var data = `
networks:
my_network:
driver: bridge
`
err := yaml.Unmarshal([]byte(data), &dn)
if err != nil {
log.Fatalf("error: %v", err)
t.Error("Could not Unmarshal the data")
}
log.Println(fmt.Sprintf("--- t:\n%v\n\n", dn))
}
I expected it to work, however I'm getting no input:
2016/12/14 13:38:12 --- t:
{{}}
what am I doing wrong?
答案1
得分: 2
我的yaml
文件是一个docker-compose.yml
文件,格式如上所述(部分内容)。我同意Marius的观点,我有未导出的字段,这是一个错误。我使用的解决方案是map
:
m := make(map[interface{}]interface{})
err = yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("错误:%v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)
英文:
My yaml
file is a docker-compose.yml
file, which is in the format described above (part of it). I agree with Marius that I have unexported fields, which is an error. The solution I used was map
:
m := make(map[interface{}]interface{})
err = yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)
答案2
得分: 0
根据你提供的内容,我为你进行了翻译:
据我所知,有两个问题,一个是具有未导出字段的数据结构,另一个是与你的数据结构不匹配的测试数据。
类似这样的代码可以帮助你:
type DockerNetwork struct {
MyNetwork struct {
Driver string `yaml:"driver"`
} `yaml:"my_network"`
}
type DockerNetworks struct {
Networks []DockerNetwork `yaml:"networks"`
}
测试数据如下:
networks:
- my_network:
driver: bridge
输出结果如下:
2016/12/14 23:47:23 --- t:
{[{{bridge}}]}
PASS
很难确定你认为的“工作”是什么意思。
英文:
AFAIKT there to things, data structures with unexported fields and test data which doesn't match your data structures.
Something like this would give you a go:
type DockerNetwork struct {
MyNetwork struct {
Driver string `yaml:driver`
} `yaml:"my_network"`
}
type DockerNetworks struct {
Networks []DockerNetwork `yaml:networks`
}
And test data:
networks:
- my_network:
driver: bridge
Gives an output:
2016/12/14 23:47:23 --- t:
{[{{bridge}}]}
PASS
And It's hard to tell, what is "working" in your opinion.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论