-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
89 lines (76 loc) · 1.58 KB
/
loader.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
package confloader
import (
"encoding/json"
"errors"
"github.com/BurntSushi/toml"
"os"
"path/filepath"
"reflect"
"time"
)
type Loader struct {
loadFile string
reloadInterval time.Duration
cancelLoopSignCh chan struct{}
conf interface{}
}
func NewLoader(loadConfigFile string, reloadInterval time.Duration, conf interface{}) *Loader {
loader := &Loader{
loadFile: loadConfigFile,
reloadInterval: reloadInterval,
cancelLoopSignCh: make(chan struct{}),
conf: conf,
}
return loader
}
func (l *Loader) WatchToLoad(errCh chan error) {
doLoad := func() {
if err := l.Load(); err != nil && errCh != nil {
errCh <- err
}
}
doLoad()
var (
reloadTicker = time.NewTicker(l.reloadInterval)
isCanceledLoop bool
)
for {
select {
case _ = <-reloadTicker.C:
doLoad()
case _ = <-l.cancelLoopSignCh:
reloadTicker.Stop()
isCanceledLoop = true
}
if isCanceledLoop {
break
}
}
}
func (l *Loader) Load() error {
buf, err := os.ReadFile(l.loadFile)
if err != nil {
return err
}
newCfgType := reflect.New(reflect.ValueOf(l.conf).Elem().Type())
newestCfg := newCfgType.Interface()
switch filepath.Ext(l.loadFile) {
case ".json":
err = json.Unmarshal(buf, newestCfg)
if err != nil {
return err
}
case ".toml":
_, err = toml.Decode(string(buf), newestCfg)
if err != nil {
return err
}
default:
return errors.New("either TOML or JSON is supported")
}
reflect.ValueOf(l.conf).Elem().Set(newCfgType.Elem())
return nil
}
func (l *Loader) CancelWatch() {
l.cancelLoopSignCh <- struct{}{}
}