使用gopkg.in/yaml.v2解析YAML时顶层数组映射为空问题求助
问题根源
你对EsxiExcludeDatastores的YAML结构和Go结构体的映射完全不匹配,存在3个核心错误:
- 配置文件中第一层的
EsxiExcludeDatastores对应的值直接是字符串数组,但你在FileConfig中把这个字段定义成了嵌套结构体,二者类型本身不匹配。 - 你定义的
EsxiExcludeDatastores结构体字段没有加yaml:"EsxiExcludeDatastores"标签,yaml.v2默认按大小写敏感匹配字段名,就算结构正确也匹配不到配置值。 - 结构体内部的
Datastores字段的tag写的是yaml:"EsxiExcludeDatastores",但你的YAML里EsxiExcludeDatastores下根本没有同名子键,自然读不到值。
解决方案
根据你是否愿意修改现有配置/代码,有两种可行改法:
方案1:不修改现有YAML配置(推荐)
直接把FileConfig中的EsxiExcludeDatastores字段类型改成字符串数组,不需要套结构体:
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"` // 直接定义为[]string匹配YAML中的数组结构,加上对应tag EsxiExcludeDatastores []string `yaml:"EsxiExcludeDatastores"` EsxiExcludeDatastores2 struct { Datastores []string `yaml:"datastores"` } `yaml:"EsxiExcludeDatastores2"` }
改完后打印len(AppConfig.EsxiExcludeDatastores)即可得到正确值2。
方案2:不修改Go结构体的嵌套结构
需要同步修改YAML配置和Go结构体tag:
修改YAML中EsxiExcludeDatastores部分,和EsxiExcludeDatastores2保持相同的嵌套结构:
EsxiExcludeDatastores: datastores: - datastore1 - datastore2
修改Go结构体,补上外层tag、修正内层tag:
EsxiExcludeDatastores struct { Datastores []string `yaml:"datastores"` // 子字段tag匹配YAML里的datastores子键 } `yaml:"EsxiExcludeDatastores"` // 外层结构体加上对应tag匹配第一层配置键
内容的提问来源于stack exchange,提问作者Dmitry S.
相关产品推荐
相关产品推荐

