-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
58 lines (45 loc) · 1.01 KB
/
config.go
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
48
49
50
51
52
53
54
55
56
57
58
package config
// 配置初始化
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Config struct {
Name string
}
// 对外的初始化配置方法
func Run(cfg string) error {
c := Config{
Name: cfg,
}
if err := c.init(); err != nil {
return err
}
c.watchConfig()
return nil
}
func (c *Config) init() error {
if c.Name != "" {
viper.SetConfigFile(c.Name)
} else {
// 默认配置文件是./config.yaml
viper.AddConfigPath(".")
viper.SetConfigName("config")
}
viper.SetConfigType("yaml")
// viper解析配置文件
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
// 简单打印下配置
fmt.Println(viper.GetString("name"))
return nil
}
func (c *Config) watchConfig() {
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
})
}