-
Notifications
You must be signed in to change notification settings - Fork 6
/
redis_drive.go
67 lines (52 loc) · 1.17 KB
/
redis_drive.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
package cookiejar
import (
"github.com/gomodule/redigo/redis"
"github.com/json-iterator/go"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type RedisDrive struct {
pool *redis.Pool
entries map[string]map[string]entry
namespaces string
}
func (r *RedisDrive) Set(key string, val map[string]entry) {
r.entries[key] = val
r.saveEntries(key)
}
func (r *RedisDrive) Get(key string) map[string]entry {
return r.entries[key]
}
func (r *RedisDrive) Delete(key string) {
delete(r.entries, key)
}
func (r *RedisDrive) saveEntries(k string) error {
conn := r.pool.Get()
defer conn.Close()
v, err := json.MarshalToString(r.entries[k])
if err != nil {
return err
}
if _, err := conn.Do("HSET", r.namespaces, k, v); err != nil {
return err
}
return nil
}
func (r *RedisDrive) readEntries() {
c := r.pool.Get()
defer c.Close()
keys, err := redis.Strings(c.Do("HKEYS", r.namespaces))
if err != nil {
return
}
for _, k := range keys {
b, err := redis.Bytes(c.Do("HGET", r.namespaces, k))
if err != nil {
continue
}
e := make(map[string]entry)
if err := json.Unmarshal(b, &e); err != nil {
// resolve fail
}
r.entries[k] = e
}
}