-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
61 lines (51 loc) · 1.08 KB
/
db.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
package cleantone
import (
"errors"
"fmt"
"log"
)
type DB struct {
Index map[string]string
PersistenceSvc PersistenceSvc
}
func NewDB(config DBConfig) *DB {
persistenceSvc, err := newPersistenceSvc(config.DataFormat, config.DataPath, config.RotateThreshold)
if err != nil {
log.Fatal(err)
}
index, err := persistenceSvc.BuildIndex()
if err != nil {
log.Fatal(err)
}
db := &DB{
Index: index,
PersistenceSvc: persistenceSvc,
}
return db
}
func (db *DB) persist(key string, value string) error {
return db.PersistenceSvc.WriteData(key, value)
}
func (db *DB) Set(key string, value string) {
db.Index[key] = value
if err := db.persist(key, value); err != nil {
log.Fatal(err)
}
}
func (db *DB) Get(key string) (string, error) {
value, ok := db.Index[key]
if !ok {
errMsg := fmt.Sprintf("Key %s not exist.", key)
return "", errors.New(errMsg)
}
return value, nil
}
func (db *DB) Close() error {
if err := db.PersistenceSvc.Flush(); err != nil {
log.Fatal(err)
}
if err := db.PersistenceSvc.Close(); err != nil {
log.Fatal(err)
}
return nil
}