-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviper.go
More file actions
47 lines (39 loc) · 978 Bytes
/
viper.go
File metadata and controls
47 lines (39 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"fmt"
"os"
"github.com/spf13/viper"
)
type SC struct {
Database
}
type Database struct {
Host string `mapstructure:"host"`
User string `mapstructure:"user"`
Dbname string `mapstructure:"dbname"`
Pwd string `mapstructure:"pwd"`
On int `mapstructure:"id"`
}
func viperDemo() {
//获取项目的执行路径
path, err := os.Getwd()
if err != nil {
panic(err)
}
config := viper.New()
config.AddConfigPath(path) //设置读取的文件路径
config.SetConfigName("config") //设置读取的文件名
config.SetConfigType("yaml") //设置文件的类型
//尝试进行配置读取
if err := config.ReadInConfig(); err != nil {
panic(err)
}
var sc SC
config.Unmarshal(&sc)
fmt.Println(sc.On)
//打印文件读取出来的内容:
//fmt.Println(config.Get("database.host"))
//fmt.Println(config.Get("database.user"))
//fmt.Println(config.Get("database.dbname"))
//fmt.Println(config.Get("database.pwd")
}