package global import ( "context" "github.com/go-redis/redis/v8" "github.com/mojocn/base64Captcha" "strings" "time" ) var Captcha *base64Captcha.Captcha const ( CaptchaPrefix = "captcha" CaptchaSeparator = ":" ) type CaptchaStore struct { Ctx context.Context Store *redis.Client } func NewCaptchaStore(redis *redis.Client) *CaptchaStore { return &CaptchaStore{ context.Background(), redis, } } func (c *CaptchaStore) Set(id string, value string) error { return c.Store.SetEX(c.Ctx, CaptchaPrefix+CaptchaSeparator+id, value, 180*time.Second).Err() } func (c *CaptchaStore) Get(id string, clear bool) string { str, err := c.Store.Get(c.Ctx, CaptchaPrefix+CaptchaSeparator+id).Result() if clear { c.Store.Del(c.Ctx, CaptchaPrefix+CaptchaSeparator+id) } if err != nil { return "" } else { return str } } func (c *CaptchaStore) Verify(id, answer string, clear bool) (match bool) { match = strings.EqualFold(c.Get(id, clear), answer) return }