-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemkeep.go
89 lines (79 loc) · 1.54 KB
/
memkeep.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 jsonmemkeep
import (
"encoding/json"
"github.com/fsnotify/fsnotify"
"io/ioutil"
"os"
"sync"
)
type Keeper struct {
fileName string
outputStruct interface{}
watcher *fsnotify.Watcher
mu *sync.RWMutex
}
func NewListener(jsonFileName string, outputStruct interface{}) *Keeper {
watcher, _ := fsnotify.NewWatcher()
watcher.Add(jsonFileName)
return &Keeper{
fileName: jsonFileName,
outputStruct: outputStruct,
watcher: watcher,
mu: new(sync.RWMutex),
}
}
func (k *Keeper) Close() {
k.watcher.Close()
}
func (k *Keeper) Run() {
k.mu.Lock()
defer k.mu.Unlock()
err := k.jsonFileToStruct(k.fileName, k.outputStruct)
if err != nil {
panic(err)
}
go func() {
for {
select {
case event, ok := <-k.watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
k.mu.Lock()
err = k.jsonFileToStruct(k.fileName, k.outputStruct)
k.mu.Unlock()
if err != nil {
panic(err)
}
}
case err, ok := <-k.watcher.Errors:
if !ok {
return
}
panic(err)
}
}
}()
}
func (k *Keeper) jsonFileToStruct(jsonFileName string, outputStruct interface{}) error {
jsonFile, err := os.Open(jsonFileName)
defer jsonFile.Close()
if err != nil {
return err
}
bytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
return err
}
err = json.Unmarshal(bytes, &outputStruct)
if err != nil {
return err
}
return nil
}
func (k *Keeper) Fetch() interface{} {
k.mu.RLock()
defer k.mu.RUnlock()
return k.outputStruct
}