-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag.go
87 lines (67 loc) · 1.54 KB
/
flag.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
package kredis
import (
"time"
"github.com/redis/go-redis/v9"
)
type Flag struct {
Proxy
}
type FlagMarkOptions struct {
expiresIn time.Duration
}
type FlagMarkOption func(*FlagMarkOptions)
func NewFlag(key string, opts ...ProxyOption) (*Flag, error) {
proxy, err := NewProxy(key, opts...)
if err != nil {
return nil, err
}
return &Flag{Proxy: *proxy}, nil
}
func NewMarkedFlag(key string, opts ...ProxyOption) (*Flag, error) {
flag, err := NewFlag(key, opts...)
if err != nil {
return nil, err
}
err = flag.Mark()
if err != nil {
return nil, err
}
return flag, nil
}
func (f *Flag) Mark(opts ...FlagMarkOption) error {
options := FlagMarkOptions{f.expiresIn}
for _, opt := range opts {
opt(&options)
}
return f.client.Set(f.ctx, f.key, 1, options.expiresIn).Err()
}
func (f *Flag) SoftMark(opts ...FlagMarkOption) error {
options := FlagMarkOptions{f.expiresIn}
for _, opt := range opts {
opt(&options)
}
return f.client.SetNX(f.ctx, f.key, 1, options.expiresIn).Err()
}
func (f *Flag) IsMarked() bool {
n, err := f.client.Exists(f.ctx, f.key).Result()
if err != nil && err != redis.Nil {
if debugLogger != nil {
debugLogger.Warn("Flag#IsMarked", err)
}
}
return n > 0
}
func (f *Flag) Remove() (err error) {
_, err = f.client.Del(f.ctx, f.key).Result()
return
}
// Mark() function optional configuration functions
func WithFlagExpiry(expires string) FlagMarkOption {
return func(o *FlagMarkOptions) {
duration, err := time.ParseDuration(expires)
if err != nil {
return
}
o.expiresIn = duration
}
}