-
Notifications
You must be signed in to change notification settings - Fork 0
/
setting.go
46 lines (38 loc) · 843 Bytes
/
setting.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
package setting
import (
"path"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Setting struct {
vp *viper.Viper
}
func NewSetting(configs ...string) (*Setting, error) {
vp := viper.New()
for _, config := range configs {
if config != "" {
configBaseName := path.Base(config)
ext := path.Ext(config)
vp.SetConfigName(strings.TrimSuffix(configBaseName, ext))
configPath := path.Dir(config)
vp.AddConfigPath(configPath)
vp.SetConfigType(ext[1:])
}
}
err := vp.ReadInConfig()
if err != nil {
return nil, err
}
s := &Setting{vp}
s.WatchSettingChange()
return s, nil
}
func (s *Setting) WatchSettingChange() {
go func() {
s.vp.WatchConfig()
s.vp.OnConfigChange(func(in fsnotify.Event) {
_ = s.ReloadAllSection()
})
}()
}