This repository has been archived by the owner on Jun 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
configStore.go
86 lines (71 loc) · 1.87 KB
/
configStore.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
package main
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
"gopkg.in/yaml.v2"
)
type ConfigStore struct {
WgConfig string `yaml:"wgConfig"`
RefreshRate int64 `yaml:"refreshRate"`
configChange chan interface{}
watcher *fsnotify.Watcher
}
func (c *ConfigStore) Update() {
filePrefix, _ := filepath.Abs(configName)
file, err := os.OpenFile(filePrefix, os.O_RDONLY, 0444)
if err != nil {
log.Println("Error opening config file:", err)
return
}
data, err := ioutil.ReadAll(file)
if err != nil {
log.Println("Error reading config file:", err)
return
}
if err := yaml.Unmarshal(data, c); err != nil {
log.Println("Error marshalling config file:", err)
return
}
}
func (c *ConfigStore) Watch() {
var err error
c.watcher, err = fsnotify.NewWatcher()
if err != nil {
log.Println("Error setting config watcher:", err)
return
}
if err = c.watcher.Add(configName); err != nil {
log.Println("Error adding config watcher:", err)
return
}
c.configChange = make(chan interface{})
go func() {
for {
select {
case w := <-c.watcher.Events:
if w.Op == fsnotify.Write {
filePrefix, _ := filepath.Abs(configName)
log.Println("Updating from config file", filePrefix)
c.configChange <- struct{}{}
}
case <-c.watcher.Errors:
c.Close()
}
}
}()
}
func (c *ConfigStore) Close() {
//close(c.configChange)
if err := c.watcher.Close(); err != nil {
log.Println("Error closing watcher:", err)
}
}
func NewConfig() *ConfigStore {
conf := &ConfigStore{}
conf.Update()
conf.Watch()
return conf
}