-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
71 lines (58 loc) · 1.11 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
62
63
64
65
66
67
68
69
70
71
package memkvdb
import (
"context"
"errors"
"time"
)
var (
ErrNotFound = errors.New("key not found")
ErrStoreRequired = errors.New("store required")
)
type MemStore interface {
Set(key DBKey, val []byte) error
Get(key DBKey) ([]byte, error)
Del(key DBKey)
}
type DB struct {
expiration time.Duration
store MemStore
}
func New(expiration time.Duration, store MemStore) (*DB, error) {
if store == nil {
return nil, ErrStoreRequired
}
db := &DB{
expiration: expiration,
store: store,
}
return db, nil
}
func NewDefault(expiration time.Duration) (*DB, error) {
var store MemStore
store = CreateMapStore()
return New(expiration, store)
}
func (db *DB) Set(key, val []byte) error {
hash, err := hash(key)
if err != nil {
return err
}
err = db.store.Set(hash, val)
if err != nil {
return err
}
// TTL
ctx, _ := context.WithTimeout(context.Background(), db.expiration)
go func() {
<-ctx.Done()
db.store.Del(hash)
}()
return nil
}
func (db *DB) Get(key []byte) ([]byte, error) {
hash, err := hash(key)
if err != nil {
return nil, err
}
return db.store.Get(hash)
}