redis.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package captcha
  2. import (
  3. "context"
  4. "time"
  5. "github.com/mojocn/base64Captcha"
  6. "go.uber.org/zap"
  7. "server/global"
  8. )
  9. func NewDefaultRedisStore() *RedisStore {
  10. return &RedisStore{
  11. Expiration: time.Second * 180,
  12. PreKey: "CAPTCHA_",
  13. Context: context.TODO(),
  14. }
  15. }
  16. type RedisStore struct {
  17. Expiration time.Duration
  18. PreKey string
  19. Context context.Context
  20. }
  21. func (rs *RedisStore) UseWithCtx(ctx context.Context) base64Captcha.Store {
  22. rs.Context = ctx
  23. return rs
  24. }
  25. func (rs *RedisStore) Set(id string, value string) error {
  26. err := global.GVA_REDIS.Set(rs.Context, rs.PreKey+id, value, rs.Expiration).Err()
  27. if err != nil {
  28. global.GVA_LOG.Error("RedisStoreSetError!", zap.Error(err))
  29. return err
  30. }
  31. return nil
  32. }
  33. func (rs *RedisStore) Get(key string, clear bool) string {
  34. val, err := global.GVA_REDIS.Get(rs.Context, key).Result()
  35. if err != nil {
  36. global.GVA_LOG.Error("RedisStoreGetError!", zap.Error(err))
  37. return ""
  38. }
  39. if clear {
  40. err := global.GVA_REDIS.Del(rs.Context, key).Err()
  41. if err != nil {
  42. global.GVA_LOG.Error("RedisStoreClearError!", zap.Error(err))
  43. return ""
  44. }
  45. }
  46. return val
  47. }
  48. func (rs *RedisStore) Verify(id, answer string, clear bool) bool {
  49. key := rs.PreKey + id
  50. v := rs.Get(key, clear)
  51. return v == answer
  52. }