1、安装依赖;
go get gopkg.in/yaml.v2
2、添加配置文件config.yaml;
redis: port: 3306 user: redis mysql: userName: root passWord: mysql
3、编写go代码读取配置文件数据;
package main import ( "fmt" "gopkg.in/yaml.v2" "os" ) type conf struct { Redis struct { Port int64 `yaml:"port"` User string `yaml:"user"` } `yaml:"redis"` Mysql struct { UserName string `yaml:"userName"` PassWord string `yaml:"passWord"` } `yaml:"mysql"` } var ConfigData *conf func loadConfig() error { config := new(conf) yamlFile, err := os.ReadFile("./config.yaml") if err != nil { return err } err = yaml.Unmarshal(yamlFile, config) if err != nil { return err } ConfigData = config return nil } func main() { err := loadConfig() if err != nil { fmt.Println(err) return } fmt.Println(ConfigData.Redis) fmt.Println(ConfigData.Mysql) } // {3309 redis} // {root mysql}