go读取yaml文件配置
config.yaml文件如下
mysql:
host: localhost
port: 3306
username: myuser
password: mypassword
database: mydatabase
读取
package main
import (
"github.com/spf13/viper"
)
func main() {
// 设置配置文件名和路径(可选)
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
// 读取配置文件
err := viper.ReadInConfig()
if err != nil {
panic(err)
}
// 读取MySQL配置信息
mysqlHost := viper.GetString("mysql.host")
mysqlPort := viper.GetInt("mysql.port")
mysqlUsername := viper.GetString("mysql.username")
mysqlPassword := viper.GetString("mysql.password")
mysqlDatabase := viper.GetString("mysql.database")
}
标签:06,读取,GetString,学习,yaml,viper,mysql,go
From: https://www.cnblogs.com/nltack/p/18187714