-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
117 lines (98 loc) · 2.27 KB
/
config.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
109
110
111
112
113
114
115
116
117
package main
import (
"encoding/json"
"log"
"os"
"sync"
"time"
"github.com/fsnotify/fsnotify"
)
var (
config *Config
watchr *fsnotify.Watcher
configLock *sync.RWMutex
)
func init() {
configLock = &sync.RWMutex{}
}
//GetConfig Obtains config safely
func GetConfig() *Config {
configLock.RLock()
defer configLock.RUnlock()
return config
}
func loadConfig(path string, fail bool) bool {
configFile, err := os.Open(path)
if err != nil {
log.Println("Error opening config file", err.Error())
if fail {
os.Exit(1)
} else {
return false
}
}
var temp *Config
jsonParser := json.NewDecoder(configFile)
if err = jsonParser.Decode(&temp); err != nil {
log.Println("Error parsing config file", err.Error())
if fail {
os.Exit(1)
} else {
return false
}
}
configLock.Lock()
config = temp
configLock.Unlock()
return true
}
// WatchConfig Adds `path` to watchr and returns a reload channel that application should use to handle config reload.
func WatchConfig(path string) (chan struct{}, chan struct{}) {
if watchr != nil {
log.Fatalln("Already watching.")
}
var err error
watchr, err = fsnotify.NewWatcher()
if err != nil {
log.Fatalln("Failed creating watcher", err.Error())
}
loadConfig(path, true)
reloadChan := make(chan struct{})
reloadedChan := make(chan struct{})
isWorking := false
go func() {
for {
select {
case event := <-watchr.Events:
if isWorking {
log.Println("Already in process of reloading, try again later.")
continue
}
if event.Op&fsnotify.Write == fsnotify.Write {
isWorking = true
go func() {
log.Println("Config file change has been detected, attempting to parse new config.")
ok := loadConfig(path, false)
if !ok {
log.Println("New config encountered error, continuing with old one.")
} else {
log.Println("New config is valid, reloading.")
reloadChan <- struct{}{}
// Prevents double reloads, thanks fsnotify...
<-reloadedChan
time.Sleep(1 * time.Second)
}
isWorking = false
}()
}
case err := <-watchr.Errors:
log.Println("Error:", err)
}
}
}()
err = watchr.Add(path)
if err != nil {
log.Fatalln("Failed to add config file to watcher", err)
}
return reloadChan, reloadedChan
}