前言
viper 支持Yaml、Json、 TOML、HCL 等格式,读取非常的方便。
安装
go get github.com/spf13/viper
demo
config.yaml:
TimeStamp: "2018-10-18 10:09:23"
Address: "Shenzhen"
Postcode: 518000
CompanyInfomation:
Name: "Sunny"
MarketCapitalization: 50000000
EmployeeNum: 200
Department:
- "Finance"
- "Design"
- "Program"
- "Sales"
IsOpen: false
main.go
package main
import (
"fmt"
"github.com/spf13/viper"
)
func main(){
v := viper.New()
v.SetConfigName("config") //文件名
v.AddConfigPath("./aTest/config") // 路径
//windows环境下为%GOPATH,linux环境下为$GOPATH
//v.AddConfigPath("%GOPATH/src/")
//设置配置文件类型
v.SetConfigType("yaml")
if err := v.ReadInConfig();err != nil {
fmt.Printf("err:%s\n",err)
}
fmt.Printf(
`
TimeStamp:%s
CompanyInfomation.Name:%s
CompanyInfomation.Department:%s `,
v.Get("TimeStamp"),
v.Get("CompanyInfomation.Name"),
v.Get("CompanyInfomation.Department"),
)
/*
result:
TimeStamp:2018-10-18 10:09:23
CompanyInfomation.Name:Sunny
CompanyInfomation.Department:[Finance Design Program Sales]
*/
}