-
Notifications
You must be signed in to change notification settings - Fork 0
/
defaults.go
108 lines (97 loc) · 1.99 KB
/
defaults.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
97
98
99
100
101
102
103
104
105
106
107
108
package auto_config
import (
"github.com/huckops/auto_config/loader"
"github.com/huckops/auto_config/reader"
"sync"
)
type Config struct {
opts Options
snapshot loader.SnapShot
sync.RWMutex
exit chan bool
}
func NewConfig(opts ...Option) (*Config, error) {
options := Options{
Reader: reader.NewReader(),
}
for _, opt := range opts {
opt(&options)
}
// 源文件放入装载器
options.Loader = loader.NewLoader(loader.WithReader(options.Reader))
// 首次读取文件
err := options.Loader.Load(options.Source...)
// 启用异常跳过,主要应对文件修改错误或者误操作问题
options.Loader.EnableReaderPanicSkip()
if err != nil {
return &Config{}, err
}
config := Config{
opts: options,
}
err = config.Init()
if err != nil {
return nil, err
}
return &config, nil
}
func (config *Config) Init() error {
// 获取初始状态
config.snapshot = config.opts.Loader.Snapshot()
// 初次解析
err := config.Scan()
if err != nil {
return err
}
// 初次运行初始化
for _, callback := range config.opts.InitCallBack {
callback()
}
return nil
}
func (config *Config) Scan() error {
return config.opts.Reader.Scan(config.snapshot.LastChange.Data, &config.opts.Entity)
}
func (config *Config) Watcher() {
watch := func(w loader.Watcher) error {
for {
snapshot, err := w.Next()
//fmt.Println(snapshot, err)
if err != nil {
return err
}
config.Lock()
config.snapshot = *snapshot
err = config.Scan()
if err != nil {
config.Unlock()
return err
}
for _, callback := range config.opts.InitCallBack {
callback()
}
config.Unlock()
}
}
for {
loadWatcher := config.opts.Loader.Watcher()
configBreak := make(chan bool)
go func() {
select {
case <-configBreak:
//case <-config.exit:
}
_ = loadWatcher.Stop()
}()
//go watch(loadWatcher)
//select {}
if err := watch(loadWatcher); err != nil {
//fmt.Println(err)
}
close(configBreak)
select {
case <-configBreak:
return
}
}
}