forked from 0xakk0r0kamui/constant-chain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keycache.go
69 lines (58 loc) · 1.29 KB
/
keycache.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
package main
import (
"encoding/json"
"fmt"
"os"
)
/*
This is a utility to save data key-value into file
*/
type KeyCache struct {
filePath string
data map[string]interface{}
}
func (keyCache *KeyCache) Load(filePath string) error {
keyCache.data = map[string]interface{}{}
keyCache.filePath = filePath
_, err := os.Stat(filePath)
if os.IsNotExist(err) {
return nil
}
r, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("%s error opening file: %v", filePath, err)
}
defer r.Close()
dec := json.NewDecoder(r)
err = dec.Decode(&keyCache.data)
if err != nil {
return fmt.Errorf("error reading %s: %v", filePath, err)
}
return nil
}
func (keyCache *KeyCache) Save() error {
w, err := os.Create(keyCache.filePath)
if err != nil {
Logger.log.Infof("Error opening file %s: %v", keyCache.filePath, err)
return err
}
enc := json.NewEncoder(w)
defer w.Close()
if err := enc.Encode(&keyCache.data); err != nil {
Logger.log.Infof("Failed to encode file %s: %v", keyCache.filePath, err)
return err
}
return nil
}
func (keyCache *KeyCache) Set(key string, value interface{}) error {
keyCache.data[key] = value
return nil
}
func (keyCache *KeyCache) Get(key string) interface{} {
value, ok := keyCache.data[key]
if ok {
return value
} else {
return nil
}
}