generated from clevergo/pkg-template
-
Notifications
You must be signed in to change notification settings - Fork 8
/
store.go
97 lines (82 loc) · 1.76 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright 2020 CleverGo. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
package redisstore
import (
"time"
"github.com/clevergo/captchas"
"github.com/go-redis/redis/v7"
)
// Option is a function that receives a pointer of redis store.
type Option func(s *Store)
// Prefix sets the prefix of key.
func Prefix(prefix string) Option {
return func(s *Store) {
s.prefix = prefix
}
}
// Expiration sets the expiration.
func Expiration(expiration time.Duration) Option {
return func(s *Store) {
s.expiration = expiration
}
}
// Store is a redis store.
type Store struct {
client *redis.Client
expiration time.Duration
prefix string
}
// New returns a redis store.
func New(client *redis.Client, opts ...Option) *Store {
s := &Store{
client: client,
prefix: "captchas",
expiration: 10 * time.Minute,
}
for _, f := range opts {
f(s)
}
return s
}
func (s *Store) getKey(id string) string {
return s.prefix + ":" + id
}
// Get implements Store.Get.
func (s *Store) Get(id string, clear bool) (string, error) {
key := s.getKey(id)
tx := s.client.TxPipeline()
get := tx.Get(key)
var del *redis.IntCmd
if clear {
del = tx.Del(key)
}
_, err := tx.Exec()
if err != nil {
return "", err
}
val, err := get.Result()
isNil := false
if err != nil {
isNil = err == redis.Nil
if isNil {
return "", captchas.ErrCaptchaIncorrect
}
return "", err
}
if clear && !isNil {
if _, err = del.Result(); err != nil {
return "", err
}
}
return val, nil
}
// Set implements Store.Set.
func (s *Store) Set(id string, value string) error {
key := s.getKey(id)
_, err := s.client.Set(key, value, s.expiration).Result()
if err != nil {
return err
}
return nil
}