-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (81 loc) · 1.92 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"sync"
)
type KeyValueStore struct {
data map[string]string
mu sync.RWMutex
}
func NewKeyValueStore() *KeyValueStore {
return &KeyValueStore{
data: make(map[string]string),
}
}
func (kv *KeyValueStore) Create(key, value string) {
kv.mu.Lock()
defer kv.mu.Unlock()
kv.data[key] = value
}
func (kv *KeyValueStore) Read(key string) string {
kv.mu.RLock()
defer kv.mu.RUnlock()
return kv.data[key]
}
func (kv *KeyValueStore) Update(key, value string) {
kv.mu.Lock()
defer kv.mu.Unlock()
kv.data[key] = value
}
func (kv *KeyValueStore) Delete(key string) {
kv.mu.Lock()
defer kv.mu.Unlock()
delete(kv.data, key)
}
func saveToFile(kv *KeyValueStore, filename string) error {
kv.mu.RLock()
defer kv.mu.RUnlock()
data, err := json.Marshal(kv.data)
if err != nil {
return err
}
err = ioutil.WriteFile(filename, data, 0644)
if err != nil {
return err
}
return nil
}
func loadFromFile(kv *KeyValueStore, filename string) error {
kv.mu.Lock()
defer kv.mu.Unlock()
data, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
err = json.Unmarshal(data, &kv.data)
if err != nil {
return err
}
return nil
}
func mai() {
kvStore := NewKeyValueStore()
filename := "kvstore.json"
err := loadFromFile(kvStore, filename)
if err != nil {
fmt.Println("No existing data found, starting with an empty store")
} else {
fmt.Println("Loaded existing data from file")
}
kvStore.Create("key2", "value")
kvStore.Create("key3", "value")
kvStore.Create("key4", "value")
err = saveToFile(kvStore, filename)
if err != nil {
fmt.Printf("Error saving data to file: %v\n", err)
} else {
fmt.Println("Data successfully saved to file")
}
}