-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathfile_kv_store.go
More file actions
55 lines (48 loc) · 1.12 KB
/
file_kv_store.go
File metadata and controls
55 lines (48 loc) · 1.12 KB
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
package main
import (
"context"
"encoding/json"
"os"
"sync"
)
// fileKVStore implements corelib/skill.KVStore using a single JSON file.
// Thread-safe. Suitable for low-write-frequency settings like source control.
type fileKVStore struct {
path string
mu sync.Mutex
data map[string]string
}
func newFileKVStore(path string) *fileKVStore {
s := &fileKVStore{path: path, data: make(map[string]string)}
s.loadFromDisk()
return s
}
func (s *fileKVStore) Get(_ context.Context, key string) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.data[key], nil
}
func (s *fileKVStore) Set(_ context.Context, key, value string) error {
s.mu.Lock()
defer s.mu.Unlock()
if value == "" {
delete(s.data, key)
} else {
s.data[key] = value
}
return s.saveToDisk()
}
func (s *fileKVStore) loadFromDisk() {
data, err := os.ReadFile(s.path)
if err != nil {
return // file doesn't exist yet — start empty
}
_ = json.Unmarshal(data, &s.data)
}
func (s *fileKVStore) saveToDisk() error {
data, err := json.MarshalIndent(s.data, "", " ")
if err != nil {
return err
}
return os.WriteFile(s.path, data, 0o644)
}