【发布时间】:2018-08-04 06:49:10
【问题描述】:
我有一个 yaml 文件,目前写成:
keys:
- key: secret/dog
values:
- username: shiba
- password: inu
- key: secret/cat
values:
- dbhost: localhost
- words: meow
但是,这个 yaml 文件经常更改,因此每次可以添加具有不同值的新条目:
keys:
- key: secret/dog
values:
- username: shiba
- password: inu
- key: secret/cat
values:
- dbhost: localhost
- words: meow
- key: secret/mouse
values:
- color: white
- key: secret/clouds
values:
- type: fluffy
我知道 go 使用 gopkg.in/yaml.v2 包,如果所有值都相同,我可以解析 yaml 文件,例如:
type Secrets struct {
Keys []struct {
Key string `json:"key"`
Values []struct {
Username string `json:"username"`
Password string `json:"password"`
} `json:"values"`
} `json:"keys"`
}
func main() {
var secret Secrets
reader, err := os.Open("demo.yml")
if err != nil {
log.Fatal(err)
}
buf, _ := ioutil.ReadAll(reader)
yaml.Unmarshal(buf, &secret)
fmt.Printf("%+v\n", secret.Keys[1].Key)
}
在上面的例子中,它只对密钥/狗密钥有效,对其他密钥无效。
当经常向我的 yaml 文件中添加新值时,如何在 Go 中执行此操作?
谢谢
【问题讨论】: