读取配置文件
使用viper读取json
、yaml
或者其他配置文件
- 目录结构
shell
.
├── config
│ ├── user.json
│ └── user.yaml
├── go.mod
├── go.sum
└── main.go
user.yaml
yaml
user1:
username: zs
password: 123456
attributes:
height: 180
bodyHeight: 130
like:
- run
- fitness
user2:
username: ls
password: 258369
attributes:
height: 178
bodyHeight: 128
like:
- pingpang
user.json
json
{
"user1": {
"username": "zs",
"password": "123456",
"attributes": {
"height": 180,
"bodyHeight": 130
},
"like": [
"run",
"fitness"
]
},
"user2": {
"username": "ls",
"password": "258369",
"attributes": {
"height": 178,
"bodyHeight": 128
},
"like": [
"pingpang"
]
}
}
main.go
Go
package main
import (
"fmt"
"github.com/spf13/viper"
)
func readConfig(viperInstance *viper.Viper) {
if err := viperInstance.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired 文件未找到
fmt.Println("文件未找到")
return
}
// Config file was found but another error was produced 找到配置文件但是出现了其他错误
fmt.Println("文件已找到,但出现其他错误", err)
return
}
user1Name := viperInstance.GetString("user1.username")
user1Height := viperInstance.GetInt("user1.attributes.height")
user1Like := viperInstance.GetStringSlice("user1.like")
fmt.Printf("user1name => %v, user1Height => %v, user1Like 1 => %v \n", user1Name, user1Height, user1Like[1])
user2Password := viperInstance.GetString("user2.password")
user2BodyHeight := viperInstance.GetInt("user2.attributes.bodyHeight")
fmt.Printf("user2Password => %v, user2BodyHeight => %v \n", user2Password, user2BodyHeight)
}
func readYaml() {
yamlConfigInstance := viper.New() // 创建viper实例
yamlConfigInstance.AddConfigPath("config/") // 设置配置文件所在目录
yamlConfigInstance.SetConfigName("user") // 设置配置文件名称
yamlConfigInstance.SetConfigType("yaml") // 设置配置文件类型
readConfig(yamlConfigInstance)
}
func readJson() {
jsonConfigInstance := viper.New();
jsonConfigInstance.AddConfigPath("config")
jsonConfigInstance.SetConfigName("user")
jsonConfigInstance.SetConfigType("json") //
readConfig(jsonConfigInstance)
}
func main() {
readYaml()
readJson()
}