-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis-client.go
2962 lines (2229 loc) · 67.4 KB
/
redis-client.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package redisclient
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
)
type RedisClient struct {
conn net.Conn
reader bufio.Reader
Opts
}
type RedisOptions struct {
Opts
}
type Opts struct {
host string
port int
db int
username string
password string
ssl bool
socketTimeout time.Duration //timeout for
socketConnectTimeout time.Duration //timeout for connecting to indicated host and port
socketKeepAliveInterval time.Duration
connectionPool *ConnectionPool
encoding string
encodingErrors string
charset string
errors []error
decodeResponses bool
retryOnTimeout bool
retryOnError []error
sslKeyFile string
sslCertFile string
sslCertReqs string
sslCaCerts string
sslCaPath string
sslCaData []byte
sslCheckhostname bool
sslPassword string
sslValidateOcsp bool
sslValidateOcspstapled bool
sslOcspContext interface{} // this might need a more specific type
sslocspexpectedcert []byte
maxconnections int
singleConnectionClient bool
healthcheckInterval time.Duration
clientname string
libname string
libversion string
retry *RetryOptions
redisConnectFunc RedisConnectFunc
credentialProvider CredentialProvider
protocol int
}
// TODO: Fill in
type RetryOptions struct{}
type CredentialProvider struct{}
type ConnectionPool struct{}
type RedisConnectFunc func() (net.Conn, error)
type MemoryUsageOpts struct {
samples int
}
type FlushAllOpts struct {
mode string
}
type FlushDbOpts struct {
mode string
}
type CommandListOpts struct {
filterby string
}
type BgsaveOpts struct {
schedule bool
}
type ClientUnblockOpts struct {
timeout bool
error bool
}
type BitcountOpts struct {
start int
end int
bit string
}
type ClientUnblockOptsFunc func(*ClientUnblockOpts)
type ClientTrackingOption func(*clientTrackingOptions)
type FlushAllOptsFunc func(*FlushAllOpts)
type FlushDbOptsFunc func(*FlushDbOpts)
type MemoryUsageOptsFunc func(*MemoryUsageOpts)
type ReplicaOfOptsFunc func(*ReplicaOfOpts)
type AclCatOpts struct {
cat string
}
type AclCatOptsFunc func(*AclCatOpts)
type ReplicaOfOpts struct {
host string
}
type clientTrackingOptions struct {
on bool
redirect int
prefix []string
bcast bool
optin bool
optout bool
noLoop bool
}
type LCSOptions struct {
LEN bool
IDX bool
MINMATCHLEN int
WITHMATCHLEN bool
}
// LCSOptsFunc is a function type for setting LCS options
type SetOpts struct {
NX bool
XX bool
Get bool
EX int64 //seconds item exists for
PX int64 //milliseconds item exists for
EXAT *time.Time
PXAT *time.Time
KeepTTL bool
}
type HExpireOpts struct {
NX bool
XX bool
GT bool
LT bool
Duration *time.Duration
}
type LPopOpts struct {
count int64
}
type SScanOpts struct {
Match string
Count int
}
type LPosOpts struct {
rank int64
count int64
maxlen int64
}
type RPopOpts struct {
count int64
}
type GetexOpts struct {
EX *time.Duration
PX *time.Duration
EXAT *time.Time
PXAT *time.Time
Persist bool
}
type BitfieldOperation struct {
Op string // GET, SET, or INCRBY
Encoding string // i for signed, u for unsigned, followed by bit count
Offset int // Bit offset
Value int64 // Used for SET and INCRBY operations
}
type BitfieldRoOperation struct {
Encoding string // i for signed, u for unsigned, followed by bit count
Offset int // Bit offset
Value int64 // Used for SET and INCRBY operations
}
// BitfieldOptions represents additional options for the BITFIELD command
type BitfieldOptions struct {
Overflow string // WRAP, SAT, or FAIL
}
type LPosOptsFunc func(*LPosOpts)
type LPopFunc func(*LPopOpts)
type RPopOptsFunc func(*RPopOpts)
type OptsFunc func(*Opts)
type SetOptsFunc func(*SetOpts)
type HExpireOptsFunc func(*HExpireOpts)
type SScanOptsFunc func(*SScanOpts)
type GetexOptsFunc func(*GetexOpts)
type LCSOptsFunc func(*LCSOptions)
type BitcountOptsFunc func(*BitcountOpts)
type BgsaveOptsFunc func(*BgsaveOpts)
type CommandListOptsFunc func(*CommandListOpts)
func WithSyncFlushDb() FlushDbOptsFunc {
return func(opts *FlushDbOpts) {
opts.mode = "SYNC"
}
}
func WithAsyncFlushDb() FlushDbOptsFunc {
return func(opts *FlushDbOpts) {
opts.mode = "ASYNC"
}
}
func WithFilterByCommandList(modifier string) CommandListOptsFunc {
return func(opts *CommandListOpts) {
opts.filterby = modifier
}
}
func WithSyncFlushAll() FlushAllOptsFunc {
return func(opts *FlushAllOpts) {
opts.mode = "SYNC"
}
}
func WithAsyncFlushAll() FlushAllOptsFunc {
return func(opts *FlushAllOpts) {
opts.mode = "ASYNC"
}
}
func BitfieldGet(encoding string, offset int) BitfieldOperation {
return BitfieldOperation{Op: "GET", Encoding: encoding, Offset: offset}
}
func BitfieldSet(encoding string, offset int, value int64) BitfieldOperation {
return BitfieldOperation{Op: "SET", Encoding: encoding, Offset: offset, Value: value}
}
func BitfieldIncrBy(encoding string, offset int, increment int64) BitfieldOperation {
return BitfieldOperation{Op: "INCRBY", Encoding: encoding, Offset: offset, Value: increment}
}
func WithTimeout() ClientUnblockOptsFunc {
return func(opts *ClientUnblockOpts) {
opts.timeout = true
}
}
func WithError() ClientUnblockOptsFunc {
return func(opts *ClientUnblockOpts) {
opts.error = true
}
}
func WithStartEnd(start int, end int) BitcountOptsFunc {
return func(opts *BitcountOpts) {
opts.start = start
opts.end = end
}
}
func WithOn() ClientTrackingOption {
return func(o *clientTrackingOptions) {
o.on = true
}
}
func WithOff() ClientTrackingOption {
return func(o *clientTrackingOptions) {
o.on = false
}
}
func WithRedirect(clientID int) ClientTrackingOption {
return func(o *clientTrackingOptions) {
o.redirect = clientID
}
}
func WithPrefix(prefix ...string) ClientTrackingOption {
return func(o *clientTrackingOptions) {
o.prefix = append(o.prefix, prefix...)
}
}
func WithBcast() ClientTrackingOption {
return func(o *clientTrackingOptions) {
o.bcast = true
}
}
func WithOptin() ClientTrackingOption {
return func(o *clientTrackingOptions) {
o.optin = true
}
}
func WithOptout() ClientTrackingOption {
return func(o *clientTrackingOptions) {
o.optout = true
}
}
func WithNoLoop() ClientTrackingOption {
return func(o *clientTrackingOptions) {
o.noLoop = true
}
}
func WithBit(bit string) BitcountOptsFunc {
return func(opts *BitcountOpts) {
opts.bit = bit
}
}
func WithLen() LCSOptsFunc {
return func(opts *LCSOptions) {
opts.LEN = true
}
}
func WithIDX() LCSOptsFunc {
return func(opts *LCSOptions) {
opts.IDX = true
}
}
func WithMinMatchLen(length int) LCSOptsFunc {
return func(opts *LCSOptions) {
opts.MINMATCHLEN = length
}
}
func WithMatchLen() LCSOptsFunc {
return func(opts *LCSOptions) {
opts.WITHMATCHLEN = true
}
}
func WithEX(seconds time.Duration) GetexOptsFunc {
return func(opts *GetexOpts) {
opts.EX = &seconds
}
}
func WithPX(milliseconds time.Duration) GetexOptsFunc {
return func(opts *GetexOpts) {
opts.PX = &milliseconds
}
}
func WithEXAT(timestamp time.Time) GetexOptsFunc {
return func(opts *GetexOpts) {
opts.EXAT = ×tamp
}
}
func WithPXAT(timestamp time.Time) GetexOptsFunc {
return func(opts *GetexOpts) {
opts.PXAT = ×tamp
}
}
func WithPersist() GetexOptsFunc {
return func(opts *GetexOpts) {
opts.Persist = true
}
}
func WithNXSet() SetOptsFunc {
return func(o *SetOpts) {
o.NX = true
o.XX = false // NX and XX are mutually exclusive
}
}
func WithXXSet() SetOptsFunc {
return func(o *SetOpts) {
o.XX = true
o.NX = false // NX and XX are mutually exclusive
}
}
func WithGet() SetOptsFunc {
return func(o *SetOpts) {
o.Get = true
}
}
func WithEXSet(seconds int64) SetOptsFunc {
return func(o *SetOpts) {
o.EX = seconds
o.PX = 0
o.EXAT = nil
o.PXAT = nil
o.KeepTTL = false
}
}
func WithPXSet(milliseconds int64) SetOptsFunc {
return func(o *SetOpts) {
o.PX = milliseconds
o.EX = 0
o.EXAT = nil
o.PXAT = nil
o.KeepTTL = false
}
}
func WithEXATSet(timestamp time.Time) SetOptsFunc {
return func(o *SetOpts) {
o.EXAT = ×tamp
o.EX = 0
o.PX = 0
o.PXAT = nil
o.KeepTTL = false
}
}
func WithPXATSet(timestamp time.Time) SetOptsFunc {
return func(o *SetOpts) {
o.PXAT = ×tamp
o.EX = 0
o.PX = 0
o.EXAT = nil
o.KeepTTL = false
}
}
func WithKeepTTL() SetOptsFunc {
return func(o *SetOpts) {
o.KeepTTL = true
o.EX = 0
o.PX = 0
o.EXAT = nil
o.PXAT = nil
}
}
func WithMatchSScan(pattern string) SScanOptsFunc {
return func(opts *SScanOpts) {
opts.Match = pattern
}
}
func WithCountSScan(count int) SScanOptsFunc {
return func(opts *SScanOpts) {
opts.Count = count
}
}
func NewSetOpts() *SetOpts {
return &SetOpts{}
}
func NewHExpireOpts() HExpireOpts {
return HExpireOpts{}
}
func WithNX() HExpireOptsFunc {
return func(o *HExpireOpts) {
o.NX = true
}
}
func WithXX() HExpireOptsFunc {
return func(o *HExpireOpts) {
o.XX = true
}
}
func WithGT() HExpireOptsFunc {
return func(o *HExpireOpts) {
o.GT = true
}
}
func WithLT() HExpireOptsFunc {
return func(o *HExpireOpts) {
o.LT = true
}
}
func WithCountLPop(count int64) LPopFunc {
return func(o *LPopOpts) {
o.count = count
}
}
func WithCountLPos(count int64) LPosOptsFunc {
return func(o *LPosOpts) {
o.count = count
}
}
func WithRankLPos(rank int64) LPosOptsFunc {
return func(o *LPosOpts) {
o.rank = rank
}
}
func WithMaxLenLPos(maxlen int64) LPosOptsFunc {
return func(o *LPosOpts) {
o.maxlen = maxlen
}
}
func WithCountRPop(count int64) RPopOptsFunc {
return func(o *RPopOpts) {
o.count = count
}
}
func defaultLPosOpts() LPosOpts {
return LPosOpts{
count: -1, // since count can be set to 0 to find all matches in the list, default is set to -1
//see https://redis.io/docs/latest/commands/lpos/
}
}
func defaultLPopOpts() LPopOpts {
return LPopOpts{}
}
func defaultRPopOpts() RPopOpts {
return RPopOpts{}
}
func defaultOptions() Opts {
return Opts{
host: "localhost",
port: 6379,
libname: "redis-client-go",
libversion: "0.0.1",
protocol: 2,
decodeResponses: false,
db: 0,
}
}
func WithCustomConnectFunc(connFunc RedisConnectFunc) OptsFunc {
return func(o *Opts) {
o.redisConnectFunc = connFunc
}
}
func DecodeResponses(shouldDecode bool) OptsFunc {
return func(o *Opts) {
o.decodeResponses = shouldDecode
}
}
func WithClientName(clienName string) OptsFunc {
return func(o *Opts) {
o.clientname = clienName
}
}
func WithUsername(username string) OptsFunc {
return func(o *Opts) {
o.username = username
}
}
func WithPassword(password string) OptsFunc {
return func(o *Opts) {
o.password = password
}
}
func WithSocketConnectTimeout(duration time.Duration) OptsFunc {
return func(o *Opts) {
o.socketConnectTimeout = duration
}
}
func WithSocketTimeout(duration time.Duration) OptsFunc {
return func(o *Opts) {
o.socketTimeout = duration
}
}
func WithSocketKeepAlive(enabled bool, interval time.Duration) OptsFunc {
return func(o *Opts) {
o.socketKeepAliveInterval = interval
}
}
func NewClient(host string, port int, opts ...OptsFunc) (*RedisClient, error) {
defaultOpts := defaultOptions()
for _, fn := range opts {
fn(&defaultOpts)
}
var conn net.Conn
var err error
if defaultOpts.redisConnectFunc != nil {
conn, err = defaultOpts.redisConnectFunc()
} else {
if defaultOpts.socketConnectTimeout > 0 && defaultOpts.socketTimeout > 0 {
ctx, cancel := context.WithTimeout(context.Background(), defaultOpts.socketTimeout)
defer cancel()
dialer := &net.Dialer{
Timeout: defaultOpts.socketConnectTimeout,
}
if defaultOpts.socketKeepAliveInterval > 0 {
dialer.KeepAlive = defaultOpts.socketKeepAliveInterval
}
conn, err = dialer.DialContext(ctx, "tcp", fmt.Sprintf("%s:%d", host, port))
} else {
conn, err = net.Dial("tcp", fmt.Sprintf("%s:%d", host, port))
}
}
if err != nil {
return nil, fmt.Errorf("failed to connect to redis %w", err)
}
if defaultOpts.socketTimeout > 0 {
err = conn.SetDeadline(time.Now().Add(defaultOpts.socketTimeout))
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to set connection deadline: %w", err)
}
}
client := &RedisClient{
conn: conn,
reader: *bufio.NewReader(conn),
Opts: defaultOpts,
}
auth_err := client.authenticate()
if auth_err != nil {
client.Close()
return nil, fmt.Errorf("error while authenticating %w", auth_err)
}
return client, nil
}
func (r *RedisClient) readResponse() (interface{}, error) {
line, err := r.reader.ReadString('\n')
if err != nil {
return nil, err
}
switch line[0] {
case '+':
return strings.TrimSpace(line[1:]), nil
case '-':
return nil, errors.New(strings.TrimSpace(line[1:]))
case ':':
return strconv.ParseInt(strings.TrimSpace(line[1:]), 10, 64)
case '$':
return r.readBulkString(line)
case '*':
return r.readArray(line)
default:
return nil, fmt.Errorf("unknown response type: %s", string(line[0]))
}
}
func (r *RedisClient) readBulkString(line string) (interface{}, error) {
length, err := strconv.Atoi(strings.TrimSpace(line[1:]))
if err != nil {
return nil, fmt.Errorf("error while reading bulk string %w", err)
}
if length == -1 {
return nil, nil
}
buf := make([]byte, length+2) // +2 for \r\n
_, err = r.reader.Read(buf)
if err != nil {
return "", fmt.Errorf("error while reading bulk string %w", err)
}
return string(buf[:length]), nil
}
func (r *RedisClient) readArray(line string) ([]interface{}, error) {
count, err := strconv.Atoi(strings.TrimSpace(line[1:]))
if err != nil {
return nil, err
}
if count == -1 {
return nil, nil
}
array := make([]interface{}, count)
for i := 0; i < count; i++ {
array[i], err = r.readResponse()
if err != nil {
return nil, fmt.Errorf("error while reading array response %w", err)
}
}
return array, nil
}
func (c *RedisClient) authenticate() error {
if c.username != "" && c.password != "" {
return c.authCommand("AUTH", c.username, c.password)
} else if c.password != "" {
return c.authCommand("AUTH", c.password)
}
return nil
}
func (c *RedisClient) authCommand(args ...string) error {
resp, err := c.Do(args...)
if err != nil {
return fmt.Errorf("authentication failed: %v", err)
}
if str, ok := resp.(string); ok && str == "OK" {
return nil
}
return fmt.Errorf("unexpected authentication response: %v", resp)
}
func encodeCommand(args []string) []byte {
buf := []byte{'*'}
buf = strconv.AppendInt(buf, int64(len(args)), 10)
buf = append(buf, '\r', '\n')
for _, arg := range args {
buf = append(buf, '$')
buf = strconv.AppendInt(buf, int64(len(arg)), 10)
buf = append(buf, '\r', '\n')
buf = append(buf, arg...)
buf = append(buf, '\r', '\n')
}
return buf
}
func (r *RedisClient) Close() error {
return r.conn.Close()
}
func (r *RedisClient) sendCommand(args []string) error {
encoded_command := encodeCommand(args)
_, err := r.conn.Write(encoded_command)
if err != nil {
return err
}
return err
}
func (r *RedisClient) Do(args ...string) (interface{}, error) {
if err := r.sendCommand(args); err != nil {
return nil, fmt.Errorf("%w", err)
}
return r.readResponse()
}
func (r *RedisClient) Get(key string) (interface{}, error) {
resp, err := r.Do("GET", key)
if err != nil {
return nil, err
}
return resp, nil
}
// refactor
func (r *RedisClient) Set(key string, val string, opts ...SetOptsFunc) (interface{}, error) {
args := []string{"SET", key, val}
defaultOpts := &SetOpts{}
for _, opt := range opts {
opt(defaultOpts)
}
if defaultOpts.NX {
args = append(args, "NX")
} else if defaultOpts.XX {
args = append(args, "XX")
}
if defaultOpts.Get {
args = append(args, "GET")
}
if defaultOpts.EX != 0 {
args = append(args, "EX", strconv.Itoa(int(defaultOpts.EX))) // set amount of seconds
} else if defaultOpts.PX != 0 {
args = append(args, "PX", strconv.FormatInt(int64(defaultOpts.PX), 10)) // set amount of milliseconds
} else if defaultOpts.EXAT != nil {
args = append(args, "EXAT", strconv.FormatInt(defaultOpts.EXAT.Unix(), 10)) //UNIX timestamp with seconds
} else if defaultOpts.PXAT != nil {
args = append(args, "PXAT", strconv.FormatInt(defaultOpts.PXAT.UnixNano()/int64(time.Millisecond), 10)) //UNIX timestamp with milliseconds
} else if defaultOpts.KeepTTL {
args = append(args, "KEEPTTL")
}
resp, err := r.Do(args...)
if err != nil {
return nil, err
}
if defaultOpts.Get {
if resp == nil {
return nil, nil
}
str, ok := resp.(string)
if !ok {
return nil, fmt.Errorf("unexpected response type for SET with GET: %T", resp)
}
return str, nil
}
if resp == nil {
return nil, nil // SET NX/XX condition not met
}
_, ok := resp.(string)
if !ok {
return nil, fmt.Errorf("unexpected response type for SET: %T", resp)
}
return resp, nil
}
func (r *RedisClient) Append(key string, val string) (interface{}, error) {
resp, err := r.Do("APPEND", key, val)
if err != nil {
return nil, fmt.Errorf("error while sending append command %w", err)
}
return resp, nil
}
func (r *RedisClient) Decr(key string) (interface{}, error) {
resp, err := r.Do("DECR", key)
if err != nil {
return nil, fmt.Errorf("error while sending decr command %w", err)
}
return resp, nil
}
func (r *RedisClient) Decrby(key string, decrement int64) (interface{}, error) {
resp, err := r.Do("DECRBY", key, strconv.Itoa(int(decrement)))
if err != nil {
return nil, fmt.Errorf("error while sending decrby command %w", err)
}
return resp, nil
}
func (r *RedisClient) Getdel(key string) (interface{}, error) {
resp, err := r.Do("GETDEL", key)
if err != nil {
return nil, fmt.Errorf("error while sending getdel command %w", err)
}
return resp, nil
}
func (r *RedisClient) Getex(key string, opts ...GetexOptsFunc) (interface{}, error) {
options := &GetexOpts{}
for _, opt := range opts {
opt(options)
}
args := []string{"GETEX", key}
if options.EX != nil {
args = append(args, "EX", strconv.FormatInt(int64(options.EX.Seconds()), 10))
} else if options.PX != nil {
args = append(args, "PX", strconv.FormatInt(options.PX.Milliseconds(), 10))
} else if options.EXAT != nil {
args = append(args, "EXAT", strconv.FormatInt(options.EXAT.Unix(), 10))
} else if options.PXAT != nil {
args = append(args, "PXAT", strconv.FormatInt(options.PXAT.UnixNano()/int64(time.Millisecond), 10))
} else if options.Persist {
args = append(args, "PERSIST")
}
resp, err := r.Do(args...)
if err != nil {
return nil, fmt.Errorf("error while sending GETEX command: %w", err)
}
return resp, nil
}
func (r *RedisClient) Getrange(key string, start int64, end int64) (interface{}, error) {
resp, err := r.Do("GETRANGE", key, strconv.Itoa(int(start)), strconv.Itoa(int(end)))
if err != nil {
return nil, fmt.Errorf("error while sending getrange command %w", err)
}
return resp, nil
}
// As of redis v6.20 it's deprecated, see https://redis.io/docs/latest/commands/getset/
func (r *RedisClient) Getset(key string, value string) (interface{}, error) {
resp, err := r.Do("GETSET", key, value)
if err != nil {
return nil, fmt.Errorf("error while sending getset command %w", err)
}
return resp, nil
}
func (r *RedisClient) Incr(key string) (interface{}, error) {
resp, err := r.Do("INCR", key)
if err != nil {
return nil, fmt.Errorf("error while sending incr command %w", err)
}
return resp, nil
}
func (r *RedisClient) Incrby(key string, increment int64) (interface{}, error) {
resp, err := r.Do("INCRBY", key, strconv.Itoa(int(increment)))
if err != nil {
return nil, fmt.Errorf("error while sending incrby command %w", err)
}
return resp, nil
}
func (r *RedisClient) Incrbyfloat(key string, increment int64) (interface{}, error) {
resp, err := r.Do("INCRBYFLOAT", key, strconv.Itoa(int(increment)))
if err != nil {
return nil, fmt.Errorf("error while sending incrbyfloat command %w", err)
}
return resp, nil
}
// not type safe
func (r *RedisClient) LCS(key1 string, key2 string, opts ...LCSOptsFunc) (interface{}, error) {
options := &LCSOptions{}
for _, opt := range opts {
opt(options)
}
args := []string{"LCS", key1, key2}
if options.LEN {
args = append(args, "LEN")
}
if options.IDX {
args = append(args, "IDX")
}
if options.MINMATCHLEN > 0 {
args = append(args, "MINMATCHLEN", strconv.Itoa(options.MINMATCHLEN))
}
if options.WITHMATCHLEN {
args = append(args, "WITHMATCHLEN")
}
resp, err := r.Do(args...)
if err != nil {
return nil, fmt.Errorf("error while sending lcs command: %w", err)
}
return resp, nil
}
func (r *RedisClient) MGet(key string, keys ...string) (interface{}, error) {
command_args := []string{"MGET", key}
command_args = append(command_args, keys...)
resp, err := r.Do(command_args...)
if err != nil {
return nil, fmt.Errorf("error while sending mget command %w", err)
}
return resp, nil
}
func (r *RedisClient) MSet(key string, value string, keyvalues ...string) (interface{}, error) {
command_args := []string{"MSET", key, value}
command_args = append(command_args, keyvalues...)
resp, err := r.Do(command_args...)
if err != nil {
return nil, fmt.Errorf("error while sending mset command %w", err)
}
return resp, nil
}
func (r *RedisClient) Msetnx(key string, value string, keyvalues ...string) (interface{}, error) {
command_args := []string{"MSETNX", key, value}
command_args = append(command_args, keyvalues...)
resp, err := r.Do(command_args...)
if err != nil {
return nil, fmt.Errorf("error while sending msetnx command %w", err)
}
return resp, nil
}