go解析yaml文件关键就是结构体的创建
初学go
tag字段要和yaml文件中的key对应起来,每个层级都要创建对应的结构体,有点烦
package configimport ("gopkg.in/yaml.v3""os"
)type Config struct {MysqlConfig MysqlConfig `yaml:"database"`
}type MysqlConfig struct {Host string `yaml:"host"`Port int `yaml:"port"`UserName string `yaml:"username"`Password string `yaml:"password"`
}func GetDBConfig() Config {file, err := os.ReadFile("db.yaml")if err != nil {panic(err)}var config Configerr = yaml.Unmarshal(file, &config)if err != nil {panic(err)}return config
}
database :host : "localhost"port : 3306username : "root"password : "password"