-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
88 lines (68 loc) · 1.69 KB
/
cache.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
82
83
84
85
86
87
88
package profilecreds
import (
"encoding/json"
"os"
"path"
"sync"
)
// Cache is the interface used by AssumeRoleProfileProvider to store temporary credentials
type Cache interface {
// Set adds a new value to the cache, overwritting any pre-existing value
Set(key, value string)
// Get a value from the cache. found is false if the value wasn't present
Get(key string) (value string, found bool)
}
// FileCache is a simple implementation of Cache backed by a file
type FileCache struct {
m sync.Mutex
data map[string]string
filename string
}
// NewFileCache returns a new instance of FileCache. If filename is "", a temporary location is chosen.
func NewFileCache(filename string) *FileCache {
if filename == "" {
filename = path.Join(os.TempDir(), "credentials")
}
return &FileCache{
filename: filename,
}
}
// Set adds a new value to the cache, overwritting any pre-existing value
func (f *FileCache) Set(key, value string) {
if f.data == nil {
f.readConf()
}
f.m.Lock()
f.data[key] = value
f.m.Unlock()
f.writeConf()
}
// Get a value from the cache. found is false if the value wasn't present
func (f *FileCache) Get(key string) (string, bool) {
if f.data == nil {
f.readConf()
}
f.m.Lock()
value, found := f.data[key]
f.m.Unlock()
return value, found
}
func (f *FileCache) readConf() {
f.m.Lock()
defer f.m.Unlock()
f.data = make(map[string]string)
file, err := os.Open(f.filename)
if err != nil {
return
}
json.NewDecoder(file).Decode(&f.data)
}
func (f *FileCache) writeConf() {
f.m.Lock()
defer f.m.Unlock()
file, err := os.OpenFile(f.filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return
}
json.NewEncoder(file).Encode(f.data)
}