gofiber-study/global/captcha.go
Shikong 72fb03ddbf 验证码简单实现
验证码添加 expire 超时时间
swag 添加 验证码测试
2022-10-25 11:40:24 +08:00

51 lines
1.0 KiB
Go

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, time.Duration(Config.Captcha.Expire)*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), strings.TrimSpace(answer))
return
}