-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
80 lines (65 loc) · 1.4 KB
/
store.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
package main
import (
"errors"
"go.etcd.io/bbolt"
"golang.org/x/exp/slog"
)
func Open(s string) *Store {
db, err := bbolt.Open(s, 0600, bbolt.DefaultOptions)
if err != nil {
panic(err)
}
return &Store{
db: db,
}
}
type Store struct {
db *bbolt.DB
}
func (s *Store) Close() {
s.db.Close()
}
func (s *Store) Get(user, key string) (string, error) {
var out []byte
err := s.db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(user))
if b == nil {
return errors.New("not found")
}
out = b.Get([]byte(key))
return nil
})
return string(out), err
}
func (s *Store) Set(user, key, value string) error {
return s.db.Update(func(tx *bbolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(user))
if err != nil {
return err
}
return b.Put([]byte(key), []byte(value))
})
}
func (s *Store) Delete(user, key string) error {
return s.db.Update(func(tx *bbolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(user))
if err != nil {
return err
}
return b.Delete([]byte(key))
})
}
func (s *Store) List(user string) (map[string]string, error) {
out := map[string]string{}
return out, s.db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(user))
if b == nil {
return errors.New("not found")
}
return b.ForEach(func(k, v []byte) error {
slog.Debug("list", "key", string(k), "value", string(v))
out[string(k)] = string(v)
return nil
})
})
}