forked from childe/gohangout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_watcher.go
38 lines (30 loc) · 923 Bytes
/
config_watcher.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
package main
import (
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
// watcher初始化的时候需要读取配置并返回一次configChannel
type Watcher interface {
watch(filename string, configChannel chan<- map[string]interface{}) error
}
func watchConfig(filename string, configChannel chan<- map[string]interface{}) error {
var watcher Watcher
// 这里可以声明更多的watcher,根据filename选择使用哪种类型的监听器
watcher = &FileWatcher{}
return watcher.watch(filename, configChannel)
}
type FileWatcher struct{}
func (f FileWatcher) watch(filename string, configChannel chan<- map[string]interface{}) error {
vp := viper.New()
vp.SetConfigFile(filename)
vp.WatchConfig()
vp.OnConfigChange(func(in fsnotify.Event) {
configChannel <- vp.AllSettings()
})
err := vp.ReadInConfig()
if err != nil {
return err
}
configChannel <- vp.AllSettings()
return nil
}