2 回答
TA贡献1816条经验 获得超6个赞
我认为唯一重要的问题是,在数据结构中,您已经声明为列表,但在YAML文件中,它是一个字典。如果像这样构建输入文件:Contacts
user:
name: John
contacts:
- type: email
value: test@test.com
- type: skype
value: skypeacc
然后你可以像这样阅读它:
package main
import (
"fmt"
"github.com/spf13/viper"
)
type Config struct {
User User
}
type User struct {
Name string
Contacts []Contact
}
type Contact struct {
Type string
Value string
}
func main() {
var cfg Config
viper.SetConfigName("config")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
panic(err)
}
viper.Unmarshal(&cfg)
fmt.Println("user: ", cfg.User.Name)
for _, contact := range cfg.User.Contacts {
fmt.Println(" ", contact.Type, ": ", contact.Value)
}
}
上面的代码可以按原样运行;您应该能够将其放入文件中并构建它。当我运行上面的示例时,我得到作为输出:
user: John
email : test@test.com
skype : skypeacc
TA贡献1784条经验 获得超8个赞
如果我得到你想要实现的目标是正确的,并且基于你提供的循环;for
您实际需要的是一个 YAML 序列,它是一个数组。所以你的最终YAML文件应该看起来像;
user:
name: John
contacts:
- type: email
value: test@test.com
- type: skype
value: skypeacc
- type: email
value: joe@example.com
此外,切片上的标签中有拼写错误。它应该与 YAML 密钥匹配;Contacts
type User struct {
Name string `mapstructure:"name"`
Contacts []Contact `mapstructure:"contacts"`
}
如果您希望保留原始的 YAML 文件结构,则必须为每个 YAML 键提供一个标记(和相应的结构字段),因此不可能开箱即用地循环它,因为 并且 被解析为结构字段。原始 YAML 文件的结构示例如下:emailskype
type Config struct {
Account User `mapstructure:"user"`
}
type User struct {
Name string `mapstructure:"name"`
Contacts Contacts `mapstructure:"contacts"`
}
type Contacts struct {
Email Contact `mapstructure:"email"`
Skype Contact `mapstructure:"skype"`
}
type Contact struct {
Type string `mapstructure:"type"`
Value string `mapstructure:"value"`
}
- 2 回答
- 0 关注
- 141 浏览
添加回答
举报
