1 Star 0 Fork 0

学习系统/common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
store_redis_original.go 1.77 KB
一键复制 编辑 原始数据 按行查看 历史
xxcheng123 提交于 2024-04-06 22:05 +08:00 . change package name
package captcha
import (
"context"
"gitee.com/study-helper/common/config"
"github.com/mojocn/base64Captcha"
"github.com/redis/go-redis/v9"
"github.com/zeromicro/go-zero/core/logx"
"time"
)
// NewOriginalRedisStore returns a redis store for captcha.
func NewOriginalRedisStore(r redis.UniversalClient) *OriginalRedisStore {
return &OriginalRedisStore{
Expiration: time.Minute * 5,
PreKey: config.RedisCaptchaPrefix,
Redis: r,
}
}
// OriginalRedisStore stores captcha data.
type OriginalRedisStore struct {
Expiration time.Duration
PreKey string
Context context.Context
Redis redis.UniversalClient
}
// UseWithCtx add context for captcha.
func (r *OriginalRedisStore) UseWithCtx(ctx context.Context) base64Captcha.Store {
r.Context = ctx
return r
}
// Set sets the captcha KV to redis.
func (r *OriginalRedisStore) Set(id string, value string) error {
err := r.Redis.Set(context.Background(), r.PreKey+id, value, r.Expiration).Err()
if err != nil {
logx.Errorw("error occurs when captcha key sets to redis", logx.Field("detail", err))
return err
}
return nil
}
// Get gets the captcha KV from redis.
func (r *OriginalRedisStore) Get(key string, clear bool) string {
val, err := r.Redis.Get(context.Background(), key).Result()
if err != nil {
logx.Errorw("error occurs when captcha key gets from redis", logx.Field("detail", err))
return ""
}
if clear {
_, err := r.Redis.Del(context.Background(), key).Result()
if err != nil {
logx.Errorw("error occurs when captcha key deletes from redis", logx.Field("detail", err))
return ""
}
}
return val
}
// Verify verifies the captcha whether it is correct.
func (r *OriginalRedisStore) Verify(id, answer string, clear bool) bool {
key := r.PreKey + id
v := r.Get(key, clear)
return v == answer
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/study-helper/common.git
git@gitee.com:study-helper/common.git
study-helper
common
common
v1.4.1

搜索帮助