猿问

如何使用结构迭代yml部分?

我用毒蛇。我正在尝试从具有yml配置的结构中获取信息。


type Config struct {

    Account       User           `mapstructure:"user"`      

}


type User struct {

    Name       string           `mapstructure:"name"`

    Contacts   []Contact        `mapstructure:"contact"`

}


type Contact struct {

    Type          string          `mapstructure:"type"`

    Value         string          `mapstructure:"value"`

}


func Init() *Config {

    conf := new(Config)


    viper.SetConfigType("yaml")

    viper.ReadInConfig()

    ...

    viper.Unmarshal(conf)

    return conf

}


...

config := Init()

...

for _, contact := range config.Account.Contacts {

   type := contact.type

   vlaue := contact.value

}

和配置


user:

  name: John

  contacts:

    email:

      type: email

      value: test@test.com

    skype:

      type: skype

      value: skypeacc

我可以获得这样的结构项目吗?我无法获得这样的联系人数据。可能吗?


侃侃无极
浏览 142回答 2
2回答

潇湘沐

我认为唯一重要的问题是,在数据结构中,您已经声明为列表,但在YAML文件中,它是一个字典。如果像这样构建输入文件:Contactsuser:  name: John  contacts:    - type: email      value: test@test.com    - type: skype      value: skypeacc然后你可以像这样阅读它:package mainimport (    "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

青春有我

如果我得到你想要实现的目标是正确的,并且基于你提供的循环;for您实际需要的是一个 YAML 序列,它是一个数组。所以你的最终YAML文件应该看起来像;user:  name: John  contacts:      - type: email        value: test@test.com      - type: skype        value: skypeacc      - type: email        value: joe@example.com此外,切片上的标签中有拼写错误。它应该与 YAML 密钥匹配;Contactstype User struct {   Name     string    `mapstructure:"name"`   Contacts []Contact `mapstructure:"contacts"`}如果您希望保留原始的 YAML 文件结构,则必须为每个 YAML 键提供一个标记(和相应的结构字段),因此不可能开箱即用地循环它,因为 并且 被解析为结构字段。原始 YAML 文件的结构示例如下:emailskypetype 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"`}
随时随地看视频慕课网APP

相关分类

Go
我要回答