captchaStore.go 917 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Package redis
  2. /**
  3. * @ File:
  4. * @ Date: 2021/5/12 10:29
  5. * @ Author: JYQ
  6. * @ Description:
  7. */
  8. package redis
  9. import (
  10. "sportfitness/base/errors"
  11. "time"
  12. "github.com/go-redis/redis/v8"
  13. )
  14. type CaptchaStore struct {
  15. }
  16. func (c CaptchaStore) genKey(id string) string {
  17. return prefix + ":captcha:" + id
  18. }
  19. func (c CaptchaStore) Set(id string, value string) {
  20. handleErr(getClient().Set(ctx, c.genKey(id), value, time.Minute*2).Err())
  21. }
  22. func (c CaptchaStore) Get(id string, clear bool) string {
  23. cmds, _ := getClient().TxPipelined(ctx, func(pipe redis.Pipeliner) error {
  24. key := c.genKey(id)
  25. pipe.Get(ctx, key)
  26. if clear {
  27. pipe.Del(ctx, key)
  28. }
  29. return nil
  30. })
  31. cmd := cmds[0].(*redis.StringCmd)
  32. r, err := cmd.Result()
  33. if err == redis.Nil {
  34. panic(errors.ErrVerifyCode)
  35. }
  36. return r
  37. }
  38. func (c CaptchaStore) Verify(id, answer string, clear bool) bool {
  39. v := c.Get(id, clear)
  40. return v == answer
  41. }