redis.go 1.3 KB

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