-
-
Notifications
You must be signed in to change notification settings - Fork 296
/
persistence_json.go
78 lines (62 loc) · 1.49 KB
/
persistence_json.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
package service
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
)
type JsonPersistenceService struct {
Directory string
}
func (s *JsonPersistenceService) NewStore(id string, subIDs ...string) Store {
return &JsonStore{
ID: id,
Directory: filepath.Join(append([]string{s.Directory}, subIDs...)...),
}
}
type JsonStore struct {
ID string
Directory string
}
func (store JsonStore) Reset() error {
if _, err := os.Stat(store.Directory); os.IsNotExist(err) {
return nil
}
p := filepath.Join(store.Directory, store.ID) + ".json"
if _, err := os.Stat(p); os.IsNotExist(err) {
return nil
}
return os.Remove(p)
}
func (store JsonStore) Load(val interface{}) error {
if _, err := os.Stat(store.Directory); os.IsNotExist(err) {
if err2 := os.MkdirAll(store.Directory, 0777); err2 != nil {
return err2
}
}
p := filepath.Join(store.Directory, store.ID) + ".json"
if _, err := os.Stat(p); os.IsNotExist(err) {
return ErrPersistenceNotExists
}
data, err := ioutil.ReadFile(p)
if err != nil {
return err
}
if len(data) == 0 {
return ErrPersistenceNotExists
}
return json.Unmarshal(data, val)
}
func (store JsonStore) Save(val interface{}) error {
if _, err := os.Stat(store.Directory); os.IsNotExist(err) {
if err2 := os.MkdirAll(store.Directory, 0777); err2 != nil {
return err2
}
}
data, err := json.Marshal(val)
if err != nil {
return err
}
p := filepath.Join(store.Directory, store.ID) + ".json"
return ioutil.WriteFile(p, data, 0666)
}