/
store.go
66 lines (56 loc) · 1.24 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
package glitterboot
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/sync"
)
type store interface {
Get(key string) (value string, err error)
Set(key, value string) (err error)
}
var _ store = new(fileStore)
type fileStore struct {
path string
m map[string]string
mu sync.RWMutex
}
func newFileStore(path string, createIfNotExist bool) (store, error) {
s := &fileStore{path: path}
err := s.loadORCreate(createIfNotExist)
if err != nil {
return nil, err
}
return s, nil
}
func (s *fileStore) loadORCreate(createIfNotExist bool) error {
data, err := ioutil.ReadFile(s.path)
if os.IsNotExist(err) && createIfNotExist {
s.m = map[string]string{}
return nil
}
if err != nil {
return err
}
return json.Unmarshal(data, &s.m)
}
func (s *fileStore) Get(key string) (string, error) {
s.mu.RLock()
s.mu.RUnlock()
return s.m[key], nil
}
func (s *fileStore) Set(key, value string) error {
s.mu.Lock()
s.mu.Unlock()
s.m[key] = value
b, err := json.Marshal(s.m)
if err != nil {
return errors.Errorf("Set: failed to marshal: %v", err)
}
err = ioutil.WriteFile(s.path, b, 0644)
if err != nil {
return errors.Errorf("Set: failed to update file: %v", err)
}
return nil
}