如何解决在 Viper 中访问嵌套的 YAML 结构时出现问题
最近用我的 Cobra 应用程序尝试使用 Viper 来解析我的配置,但结果我无法解析内部嵌套块。 ClustersOuter
的地图始终为空,我确信地图结构已正确标记。我更喜欢使用 Viper Unmarshall 功能而不是手动获取数据类型。
map[zones:[{ClustersOuter:map[] Id:1} {ClustersOuter:map[] Id:2}]]
不知何故,我似乎只能检索 zone
地图及其 ID,而不能检索 clusters
地图的任何地图。
我的输入:
config.yml
zones:
- id: 1
clusters:
- cluster_id: 1
k3s_config_file: "k3s-cluster-1-config.yaml"
- cluster_id: 2
k3s_config_file: "k3s-cluster-2-config.yaml"
- cluster_id: 3
k3s_config_file: "k3s-cluster-3-config.yaml"
- id: 2
clusters:
- cluster_id: 1
k3s_config_file: "k3s-cluster-1-config.yaml"
- cluster_id: 2
k3s_config_file: "k3s-cluster-2-config.yaml"
- cluster_id: 3
k3s_config_file: "k3s-cluster-3-config.yaml"
configuration.go
package config
type Zones struct {
ClustersOuter map[string][]ClustersOuter `mapstructure:"zones"`
Id int `mapstructure:"id"`
}
type ClustersInner struct {
ClusterId int `mapstructure:"cluster_id"`
K3sConfigFile string `mapstructure:"k3s_config_file"`
}
type ClustersOuter struct {
ClustersInner map[string][]ClustersInner `mapstructure:"clusters"`
}
type ConfigSuper map[string][]Zones
main.go
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.SetConfigType("yaml")
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading config file,%s",err)
return false
}
var configuration config.ConfigSuper
err := viper.Unmarshal(&configuration)
if err != nil {
log.Fatalf("unable to decode into struct,%v",err)
}
fmt.Printf("%+v\n",configuration)
解决方法
您的结构类型不反映 YAML 类型,当您只处理切片时,您似乎将映射和切片组合在一起。在 YAML 中,地图如下所示:
myMap:
key1: value1
和数组看起来像这样:
myArray:
- foo: bar
不幸的是,您的配置对象已经搞砸了,我无法理解其意图,因此我为您重新编写了它。 Viper 可以毫无问题地解码这些类型。
type Config struct {
Zones []Zone `mapstructure:"zones"`
}
type Zone struct {
ID int `mapstructure:"id"`
Clusters []Cluster `mapstructure:"clusters"`
}
type Cluster struct {
ClusterID int `mapstructure:"cluster_id"`
K3sConfigFile string `mapstructure:"k3s_config_file"`
}
Config
结构体是根对象,请确保对其进行解组。
config := Config{}
err = viper.Unmarshal(&config)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。