如何使用Go Viper包解析配置中的条目头(如customer1)?
解决方法
因为YAML中的apps是键值对形式的Map(键为customer1、customer2,值为对应配置),你之前用切片[]*AppConfig接收会丢失键名,只需将接收类型改为map[string]*AppConfig就能直接获取键名,无需修改原配置文件。
具体实现步骤
- 修改变量类型,把切片替换为Map:
// 替换原来的 appconfigs []*AppConfig appConfigs map[string]*AppConfig
- 保持Viper加载配置逻辑不变,将
apps节点Unmarshal到Map中:
viper.SetConfigName(configName) viper.SetConfigType("yaml") viper.AddConfigPath(".") // 加载配置文件 if err := viper.ReadInConfig(); err != nil { panic(err) // 实际项目建议做优雅错误处理 } // Unmarshal到Map类型 if err := viper.UnmarshalKey("apps", &appConfigs); err != nil { panic(err) }
- 遍历Map获取键名和对应配置:
for customerName, config := range appConfigs { fmt.Printf("客户名称: %s\n", customerName) fmt.Printf("上传路径: %s\n", config.UploadPath) fmt.Printf("本地路径: %s\n", config.LocalPath) fmt.Printf("Bucket: %s\n\n", config.Bucket) }
注意事项
你的原YAML配置中customer2的local_path末尾多了一个逗号,会导致解析错误,建议修正为:
apps: customer1: upload_path: "/opt/uploads/customer1" local_path: "/opt/ready/customer1" bucket: "b1" customer2: upload_path: /opt/uploads/customer2 local_path: opt/ready/customer2 # 去掉末尾的逗号 bucket: "b2"
内容的提问来源于stack exchange,提问作者user982599
相关产品推荐
相关产品推荐

