-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_driver.go
96 lines (86 loc) · 1.67 KB
/
file_driver.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 goconfig_center
import (
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"sync"
)
type fileConfig struct {
ConfigDriver `mapstructure:",squash"`
Path string `mapstructure:"path"`
Prefix string `mapstructure:"prefix"`
Type string `mapstructure:"type"`
}
type fileDriver struct {
cfg *fileConfig
viper *viper.Viper
close bool
onUpdate chan struct{}
lock *sync.Mutex
once *sync.Once
}
func (r *fileDriver) Name() string {
return r.cfg.Driver
}
func (r *fileDriver) GetViper() (*viper.Viper, error) {
return r.viper, nil
}
func (r *fileDriver) OnUpdate() <-chan struct{} {
if r.close {
return nil
}
r.lock.Lock()
defer r.lock.Unlock()
if r.onUpdate == nil {
r.onUpdate = make(chan struct{})
r.viper.OnConfigChange(func(e fsnotify.Event) {
r.lock.Lock()
if r.onUpdate != nil {
r.onUpdate <- struct{}{}
}
r.lock.Unlock()
})
r.viper.WatchConfig()
}
return r.onUpdate
}
func (r *fileDriver) Close() error {
r.lock.Lock()
defer r.lock.Unlock()
if r.close {
return nil
}
r.close = true
if r.onUpdate != nil {
close(r.onUpdate)
r.onUpdate = nil
r.viper.OnConfigChange(nil)
}
return nil
}
func (r *fileDriver) Prefix() string {
return r.cfg.Prefix
}
func fileFactory(cfg *viper.Viper) (Driver, error) {
var c fileConfig
if err := cfg.Unmarshal(&c); err != nil {
return nil, err
}
v := viper.New()
if c.Type != "" {
v.SetConfigType(c.Type)
}
v.AddConfigPath(c.Path)
err := v.ReadInConfig()
if err != nil {
return nil, err
}
return &fileDriver{
cfg: &c,
viper: v,
lock: &sync.Mutex{},
once: &sync.Once{},
}, nil
}
func init() {
Register("file", fileFactory)
}