-
Notifications
You must be signed in to change notification settings - Fork 3
/
status_store.go
60 lines (47 loc) · 1.22 KB
/
status_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
package main
import (
"bytes"
"encoding/binary"
"github.com/syndtr/goleveldb/leveldb"
)
// StatusStore represents current status cache store
type StatusStore struct {
databaseFile string
}
const (
// NotFoundKey represents value if key is not found
NotFoundKey = -1
)
// NewStatusStore create new StatusStore instance
func NewStatusStore(databaseFile string) *StatusStore {
s := new(StatusStore)
s.databaseFile = databaseFile
return s
}
// GetDbStatus returns status code for specified key
func (s *StatusStore) GetDbStatus(key string) (int, error) {
db, err := leveldb.OpenFile(s.databaseFile, nil)
if err != nil {
return 0, err
}
defer db.Close()
if ret, _ := db.Has([]byte(key), nil); !ret {
return NotFoundKey, nil
}
data, err := db.Get([]byte(key), nil)
buf := bytes.NewBuffer(data)
statusCode, _ := binary.Varint(buf.Bytes())
return int(statusCode), nil
}
// SaveDbStatus saves status code for specified key
func (s *StatusStore) SaveDbStatus(key string, statusCode int) error {
db, err := leveldb.OpenFile(s.databaseFile, nil)
if err != nil {
return err
}
defer db.Close()
buf := make([]byte, binary.MaxVarintLen32)
binary.PutVarint(buf, int64(statusCode))
db.Put([]byte(key), buf, nil)
return nil
}