合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
> Golang有很多第三方包,其中的 viper 支持读取多种配置文件信息 [TOC] ## 安装 ~~~ go get github.com/spf13/viper ~~~ ## 配置文件 /config.yml ~~~ database: host: 127.0.0.1 user: root dbname: test pwd: 123456 ~~~ ## 读取config.yml配置信息 ~~~ package main import ( "fmt" "os" "github.com/spf13/viper" ) func main() { //获取项目的执行路径 path, err := os.Getwd() if err != nil { panic(err) } config := viper.New() config.AddConfigPath(path) //设置读取的文件路径 config.SetConfigName("config") //设置读取的文件名 config.SetConfigType("yml") //设置文件的类型 //尝试进行配置读取 if err := config.ReadInConfig(); err != nil { panic(err) } //打印文件读取出来的内容: fmt.Println(config.Get("database.host")) fmt.Println(config.Get("database.user")) fmt.Println(config.Get("database.dbname")) fmt.Println(config.Get("database.pwd")) } ~~~