-
Notifications
You must be signed in to change notification settings - Fork 1
/
conf.go
54 lines (50 loc) · 1.3 KB
/
conf.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
package mcfg
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
"os"
"time"
)
// viper bug OnConfigChange 会回调2次
// https://github.com/spf13/viper/issues?q=OnConfigChange
var lastChangeTime time.Time
func init() {
lastChangeTime = time.Now()
}
func InitViperConfigFile(cfgFile string, cfg interface{}, tagName string) error {
if tagName == "" {
tagName = "viper"
}
cfgObj := viper.New()
_, err := os.Stat(cfgFile)
if err == nil {
cfgObj.SetConfigFile(cfgFile)
} else {
cfgObj.SetConfigFile(cfgFile)
cfgObj.AddConfigPath(".")
}
if err := cfgObj.ReadInConfig(); err != nil {
return fmt.Errorf("read config failed: %v", err)
}
if err := cfgObj.Unmarshal(cfg, func(c *mapstructure.DecoderConfig) {
c.TagName = tagName
}); err != nil {
return fmt.Errorf("config unmarshal filed: %v", err)
}
cfgObj.WatchConfig()
cfgObj.OnConfigChange(func(in fsnotify.Event) {
if time.Now().Sub(lastChangeTime).Seconds() >= 1 {
if err := cfgObj.Unmarshal(cfg, func(c *mapstructure.DecoderConfig) {
c.TagName = tagName
}); err != nil {
fmt.Println(fmt.Errorf("config unmarshal filed: %v", err))
}
lastChangeTime = time.Now()
fmt.Printf("配置信息: %+v\n", cfg)
}
})
fmt.Printf("配置信息:%+v\n", cfg)
return nil
}