-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.go
80 lines (63 loc) · 1.75 KB
/
database.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
package subscribe
import (
"encoding/json"
"fmt"
"os"
)
/************************
* Database Methods *
************************/
// GetDB returns an interface to manage events.
func GetDB(stateFile string) (*Subscribe, error) {
sub := &Subscribe{
stateFile: stateFile,
EnableAPIs: make([]string, 0),
Events: &Events{Map: make(map[string]*Rules)},
Subscribers: make([]*Subscriber, 0),
}
return sub, sub.StateFileLoad()
}
// StateFileLoad data from a json file.
func (s *Subscribe) StateFileLoad() error {
if s.stateFile == "" {
return nil
}
if buf, err := os.ReadFile(s.stateFile); os.IsNotExist(err) {
return s.StateFileSave()
} else if err != nil {
return fmt.Errorf("file problem: %w", err)
} else if err := json.Unmarshal(buf, s); err != nil {
return fmt.Errorf("json problem: %w", err)
}
return nil
}
// StateGetJSON returns the state data in json format.
func (s *Subscribe) StateGetJSON() (string, error) {
s.Events.RLock()
defer s.Events.RUnlock()
b, err := json.Marshal(s)
return string(b), err
}
// StateFileSave writes out the state file.
func (s *Subscribe) StateFileSave() error {
if s.stateFile == "" {
return nil
}
s.Events.RLock()
defer s.Events.RUnlock()
if buf, err := json.Marshal(s); err != nil {
return fmt.Errorf("marshaling json: %w", err)
} else if err = os.WriteFile(s.stateFile, buf, 0o600); err != nil { //nolint:gomnd
return fmt.Errorf("writing file: %w", err)
}
return nil
}
// StateFileRelocate writes the state file to a new location.
func (s *Subscribe) StateFileRelocate(newPath string) error {
s.stateFile, newPath = newPath, s.stateFile // swap places
if err := s.StateFileLoad(); err != nil {
s.stateFile = newPath // got an error, put it back.
return err
}
return nil
}