忽略的 YAML 标签

Ignored YAML tag

我有 config.yml 个文件:

vcenter:
  connection: https 
  hostname: vcenter.mydomain.lan
  username: readonlyauto@vsphere.local
  password: mypasspord
  port: 443

EsxiExcludeDatastores:
  - datastore1
  - datastore2

EsxiExcludeDatastores2:
  datastores:
    - datastore1
    - datastore2

我正在尝试用“gopkg.in/yaml.v2”解析它

我创建了结构:

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

解析后打印结果:

    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

你能帮我吗,我在 EsxiExcludeDatastores 结构中哪里出错了?如您所见,EsxiExcludeDatastores2 一切正常,但 EsxiExcludeDatastores 为空。

我尝试过以不同的方式做到这一点,但没有结果...

你快到了。

要将 yaml 结构标签“提升”到“父”字段,请添加:

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

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


yaml.v2 文档中,使用 inline 标志的结构标记执行以下操作:

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.