-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviper_config.go
96 lines (80 loc) · 1.76 KB
/
viper_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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package setting
import (
"errors"
"log"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type viperConfig struct {
vp *viper.Viper
configFile string
watchFile bool
sections map[string]interface{}
}
// Load load config
func (c *viperConfig) Load() error {
if c.configFile == "" {
return errors.New("config file is empty")
}
configDir, err := filepath.Abs(filepath.Dir(c.configFile))
if err != nil {
return err
}
// file ext
ext := strings.TrimPrefix(filepath.Ext(c.configFile), ".")
if ext == "" {
ext = "yaml" // default yaml file
}
file := filepath.Base(c.configFile)
c.vp.SetConfigName(file)
c.vp.AddConfigPath(configDir)
c.vp.SetConfigType(ext)
err = c.vp.ReadInConfig()
if err != nil {
return err
}
if c.watchFile {
c.watch()
}
return nil
}
// IsSet is set value
func (c *viperConfig) IsSet(key string) bool {
return c.vp.IsSet(key)
}
// ReadSection read val by key,val must be a pointer
func (c *viperConfig) ReadSection(key string, val interface{}) error {
err := c.vp.UnmarshalKey(key, val)
if _, ok := c.sections[key]; !ok {
c.sections[key] = val
}
return err
}
// Store save config to file
func (c *viperConfig) Store(path string) error {
return c.vp.WriteConfigAs(path)
}
func (c *viperConfig) reload() error {
for k, v := range c.sections {
err := c.ReadSection(k, v)
if err != nil {
return err
}
}
return nil
}
// when the configuration file is changed, reload all the configured keys/values
func (c *viperConfig) watch() {
go func() {
c.vp.WatchConfig()
c.vp.OnConfigChange(func(in fsnotify.Event) {
log.Println("config file has changed...")
err := c.reload()
if err != nil {
log.Printf("read all config section err:%s\n", err.Error())
}
})
}()
}