store_redis.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package captcha
  2. import (
  3. "errors"
  4. "time"
  5. "github.com/runningwater/gohub/pkg/app"
  6. "github.com/runningwater/gohub/pkg/config"
  7. "github.com/runningwater/gohub/pkg/redis"
  8. )
  9. // RedisStore is a store for captcha using Redis.
  10. // It implements the Save interface. base64Captcha.Store interface.
  11. type RedisStore struct {
  12. RedisClient *redis.RedisClient
  13. KeyPrefix string
  14. }
  15. // Set 实现 base64Captcha.Save.Set 方法
  16. func (s *RedisStore) Set(key string, value string) error {
  17. expiretime := time.Minute * time.Duration(config.GetInt64("captcha.expire_time"))
  18. // 方便本地开发调试
  19. if app.IsLocal() {
  20. expiretime = time.Minute * time.Duration(config.GetInt64("captcha.debug_expire_time"))
  21. }
  22. if ok := s.RedisClient.Set(s.KeyPrefix+key, value, expiretime); !ok {
  23. return errors.New("无法存储图片验证码")
  24. }
  25. return nil
  26. }
  27. // Get 实现 base64Captcha.Save.Get 方法
  28. func (s *RedisStore) Get(key string, clear bool) string {
  29. key = s.KeyPrefix + key
  30. val := s.RedisClient.Get(key)
  31. if clear {
  32. s.RedisClient.Del(key)
  33. }
  34. return val
  35. }
  36. // Verify 实现 base64Captcha.Save.Verify 方法
  37. func (s *RedisStore) Verify(key, answer string, clear bool) bool {
  38. v := s.Get(key, clear)
  39. return v == answer
  40. }