-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
81 lines (67 loc) · 1.42 KB
/
store.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
package main
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
"github.com/lxbot/lxlib/v2"
"github.com/lxbot/lxlib/v2/common"
"github.com/lxbot/lxlib/v2/lxtypes"
)
type M = map[string]interface{}
const fileName = "store.json"
var filePath string
var wg sync.WaitGroup
func main() {
store, getCh, setCh := lxlib.NewStore()
var dir string
if fp, err := filepath.Abs(filepath.Join("data", "store")); err == nil {
dir = fp
} else {
common.FatalLog(err)
}
if err := os.MkdirAll(dir, 0755); err != nil {
common.FatalLog(err)
}
if fp, err := filepath.Abs(filepath.Join(dir, fileName)); err == nil {
filePath = fp
} else {
common.FatalLog(err)
}
common.InfoLog("store file path:", filePath)
for {
select {
case event := <-*getCh:
onGet(event, store)
case event := <-*setCh:
onSet(event)
default:
time.Sleep(time.Millisecond)
}
}
}
func onGet(event *lxtypes.StoreEvent, store *lxlib.Store) {
m := M{}
if b, err := os.ReadFile(filePath); err == nil {
_ = json.Unmarshal(b, &m)
}
if value, ok := m[event.Key]; ok {
event.Value = value
}
store.SendGetResult(event)
}
func onSet(event *lxtypes.StoreEvent) {
m := M{}
if b, err := os.ReadFile(filePath); err == nil {
_ = json.Unmarshal(b, &m)
}
m[event.Key] = event.Value
b, err := json.Marshal(m)
if err != nil {
common.ErrorLog(err)
}
if err := os.WriteFile(filePath, b, 0600); err != nil {
common.ErrorLog(err)
}
}