-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetting.go
53 lines (44 loc) · 886 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
47
48
49
50
51
52
53
package xxxsetting
import (
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Setting struct {
vp *viper.Viper
}
func NewSettingFromEnv() (*Setting, error) {
vp := viper.New()
// viper config
vp.SetEnvPrefix("SETTINGS")
vp.AutomaticEnv()
s := &Setting{vp}
return s, nil
}
func NewSettingFromFile(configs ...string) (*Setting, error) {
vp := viper.New()
vp.SetConfigName("config")
for _, config := range configs {
if config != "" {
vp.AddConfigPath(config)
}
}
vp.SetConfigType("yaml")
err := vp.ReadInConfig()
if err != nil {
return nil, err
}
s := &Setting{vp}
s.WatchSettingChange()
return s, nil
}
func (s *Setting) Get(key string) interface{} {
return s.vp.Get(key)
}
func (s *Setting) WatchSettingChange() {
go func() {
s.vp.WatchConfig()
s.vp.OnConfigChange(func(in fsnotify.Event) {
_ = s.ReloadAllSection()
})
}()
}