最近用我的 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)