go 加载yaml配置文件
config.yaml文件
mysql:url: 127.0.0.1userName: rootpassword: rootdbname: testport: 3306
- 准备结构体
// 用于接收yaml配置参数的struct结构体
type conf struct {Mysql Mysql `yaml:"mysql"`
}type Mysql struct {Url string `yaml:"url"`UserName string `yaml:"userName"`Password string `yaml:"password"`DbName string `yaml:"dbname"`Port string `yaml:"port"`
}
- 加载yaml
func loadConfig() *conf {config := new(conf)yamlFile, err := os.ReadFile("./config/config.yaml")if err != nil {fmt.Println(err.Error())}err = yaml.Unmarshal(yamlFile, config)if err != nil {fmt.Println(err.Error())}return config
}
- 使用
// 获取yaml配置参数
conf := loadConfig()
// 将yaml参数拼接成连接数据库的url
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",conf.Mysql.UserName,conf.Mysql.Password,conf.Mysql.Url,conf.Mysql.Port,conf.Mysql.DbName,
)
