Home > database >  Ignored YAML tag
Ignored YAML tag

Time:11-16

I have config.yml file:

vcenter:
  connection: https 
  hostname: vcenter.mydomain.lan
  username: [email protected]
  password: mypasspord
  port: 443

EsxiExcludeDatastores:
  - datastore1
  - datastore2

EsxiExcludeDatastores2:
  datastores:
    - datastore1
    - datastore2

I'm trying to parse it with "gopkg.in/yaml.v2"

I created struct:

type FileConfig struct {
    Vcenter struct {
        ConnectionType string `yaml:"connection"`
        Hostname string `yaml:"hostname"`
        Username string `yaml:"username"`
        Password string `yaml:"password"`
        Port int `yaml:"port"`
    } `yaml:"vcenter"`
    EsxiExcludeDatastores struct {
        Datastores []string `yaml:"EsxiExcludeDatastores"`
    }
    EsxiExcludeDatastores2 struct {
        Datastores []string `yaml:"datastores"`
    } `yaml:"EsxiExcludeDatastores2"`
}

var AppConfig FileConfig

After parsing, I print results:

    fmt.Println("Num of EsxiExcludeDatastores.Datastores = ", len(AppConfig.EsxiExcludeDatastores.Datastores))
    fmt.Println("Num of EsxiExcludeDatastores2.Datastores = ", len(AppConfig.EsxiExcludeDatastores2.Datastores))


Num of EsxiExcludeDatastores.Datastores =  0
Num of EsxiExcludeDatastores2.Datastores =  2

Can you help me, where I did mistake in EsxiExcludeDatastores struct? As you see, everything is fine with EsxiExcludeDatastores2, but EsxiExcludeDatastores is empty.

I tried to do this in different ways, but with no result ...

CodePudding user response:

You're almost there.

To "promote" yaml struct tag(s) to the "parent" field, add:

EsxiExcludeDatastores struct {
    Datastores []string `yaml:"EsxiExcludeDatastores"`
} `yaml:",inline"`   // <- this

https://play.golang.org/p/S7QxGaspTyN


From the yaml.v2 docs, a struct tag that uses the inline flag does the following:

Inline the field, which must be a struct or a map, causing all of its fields or keys to be processed as if they were part of the outer struct. For maps, keys must not conflict with the yaml keys of other struct fields.

  • Related