Go解析字段名动态变化的YAML文件 提取指定或全部邮箱地址
实现方案
核心解决思路是用map[string]类型承接contacts下的动态团队字段,不需要预定义所有团队名称,适配后续新增的团队配置。
1. 定义结构体
type YAMLConfig struct { Contacts map[string]TeamInfo `yaml:"contacts"` } type TeamInfo struct { Email EmailInfo `yaml:"email"` } type EmailInfo struct { To string `yaml:"to"` }
其中Contacts字段是map类型,key为动态的团队名称,value为对应团队的配置信息。
2. 解析YAML文件
依赖gopkg.in/yaml.v3库完成解析,代码示例:
import ( "os" "gopkg.in/yaml.v3" ) func loadConfig(yamlPath string) (YAMLConfig, error) { var config YAMLConfig fileContent, err := os.ReadFile(yamlPath) if err != nil { return config, err } err = yaml.Unmarshal(fileContent, &config) return config, err }
3. 功能实现
提取全部邮箱地址
遍历Contacts map即可获取所有团队的邮箱:
func listAllEmails(config YAMLConfig) map[string]string { teamEmailMap := make(map[string]string) for teamName, teamInfo := range config.Contacts { teamEmailMap[teamName] = teamInfo.Email.To } return teamEmailMap }
返回结果的key为团队名,value为对应邮箱地址。
查询指定团队的邮箱
直接通过map的key查询即可:
func getTeamEmail(config YAMLConfig, teamName string) (string, bool) { teamInfo, ok := config.Contacts[teamName] if !ok { return "", false } return teamInfo.Email.To, true }
第二个返回值标识对应团队是否存在配置。
4. 完整命令行工具示例
支持运行时传入团队名称查询对应邮箱:
package main import ( "fmt" "os" "gopkg.in/yaml.v3" ) type YAMLConfig struct { Contacts map[string]TeamInfo `yaml:"contacts"` } type TeamInfo struct { Email EmailInfo `yaml:"email"` } type EmailInfo struct { To string `yaml:"to"` } func loadConfig(yamlPath string) (YAMLConfig, error) { var config YAMLConfig fileContent, err := os.ReadFile(yamlPath) if err != nil { return config, err } err = yaml.Unmarshal(fileContent, &config) return config, err } func getTeamEmail(config YAMLConfig, teamName string) (string, bool) { teamInfo, ok := config.Contacts[teamName] if !ok { return "", false } return teamInfo.Email.To, true } func main() { // 参数校验:需传入YAML文件路径和目标团队名 if len(os.Args) != 3 { fmt.Println("使用方式:./contact-query <配置文件路径> <团队名称>") os.Exit(1) } configPath := os.Args[1] targetTeam := os.Args[2] // 加载配置 config, err := loadConfig(configPath) if err != nil { fmt.Printf("配置加载失败:%s\n", err.Error()) os.Exit(1) } // 查询邮箱 email, exists := getTeamEmail(config, targetTeam) if !exists { fmt.Printf("未找到团队[%s]的邮箱配置\n", targetTeam) os.Exit(1) } fmt.Println(email) }
内容的提问来源于stack exchange,提问作者CJW
相关产品推荐
相关产品推荐

