-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
71 lines (55 loc) · 1.65 KB
/
redis.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 main
import (
"context"
"encoding/base64"
"strings"
"time"
"github.com/go-redis/redis/v8"
"github.com/jakemakesstuff/spherical/hashverifier"
)
type redisDriver struct {
redisClient *redis.Client
}
func (r redisDriver) LookupPGP(hostname string) []byte {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
hostname = strings.ToLower(hostname)
b, err := r.redisClient.Get(ctx, "pgp:"+hostname).Bytes()
if err != nil {
return nil
}
return b
}
func (r redisDriver) WritePGP(hostname string, key []byte) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
hostname = strings.ToLower(hostname)
r.redisClient.Set(ctx, "pgp:"+hostname, key, time.Hour*24*30)
}
func (r redisDriver) Exists(hash []byte) bool {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
hashS := base64.StdEncoding.EncodeToString(hash)
v, _ := r.redisClient.Get(ctx, "hash:"+hashS).Result()
return v == "1"
}
func (r redisDriver) Ensure(hash []byte) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
hashS := base64.StdEncoding.EncodeToString(hash)
r.redisClient.Set(ctx, "hash:"+hashS, "1", 0)
}
var _ hashverifier.HashCache = redisDriver{}
func newRedis(redisUrl string) (hashverifier.HashCache, error) {
opts, err := redis.ParseURL(redisUrl)
if err != nil {
return nil, err
}
client := redis.NewClient(opts)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
if err = client.Ping(ctx).Err(); err != nil {
return nil, err
}
return redisDriver{redisClient: client}, nil
}