forked from Luzifer/ots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage_redis.go
70 lines (56 loc) · 1.63 KB
/
storage_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
package main
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
redis "github.com/redis/go-redis/v9"
)
const redisDefaultPrefix = "io.luzifer.ots"
type storageRedis struct {
conn *redis.Client
}
func newStorageRedis() (storage, error) {
if os.Getenv("REDIS_URL") == "" {
return nil, fmt.Errorf("REDIS_URL environment variable not set")
}
// We replace the old URI format
// tcp://auth:[email protected]:6379/0
// with the new one
// redis://<user>:<password>@<host>:<port>/<db_number>
// in order to maintain backwards compatibility
opt, err := redis.ParseURL(strings.Replace(os.Getenv("REDIS_URL"), "tcp://", "redis://", 1))
if err != nil {
return nil, errors.Wrap(err, "parsing REDIS_URL")
}
s := &storageRedis{
conn: redis.NewClient(opt),
}
return s, nil
}
func (s storageRedis) Create(secret string, expireIn time.Duration) (string, error) {
id := uuid.Must(uuid.NewV4()).String()
err := s.conn.Set(context.Background(), s.redisKey(id), secret, expireIn).Err()
return id, errors.Wrap(err, "writing redis key")
}
func (s storageRedis) ReadAndDestroy(id string) (string, error) {
secret, err := s.conn.Get(context.Background(), s.redisKey(id)).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return "", errSecretNotFound
}
return "", err
}
err = s.conn.Del(context.Background(), s.redisKey(id)).Err()
return string(secret), errors.Wrap(err, "deleting key")
}
func (s storageRedis) redisKey(id string) string {
prefix := redisDefaultPrefix
if prfx := os.Getenv("REDIS_KEY"); prfx != "" {
prefix = prfx
}
return strings.Join([]string{prefix, id}, ":")
}