1 Star 0 Fork 0

学习系统 / common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
store_redis.go 1.63 KB
一键复制 编辑 原始数据 按行查看 历史
xxcheng123 提交于 2024-04-06 22:05 . change package name
package captcha
import (
"context"
"gitee.com/study-helper/common/config"
"github.com/mojocn/base64Captcha"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
"time"
)
// NewRedisStore returns a redis store for captcha.
func NewRedisStore(r *redis.Redis) *RedisStore {
return &RedisStore{
Expiration: time.Minute * 5,
PreKey: config.RedisCaptchaPrefix,
Redis: r,
}
}
// RedisStore stores captcha data.
type RedisStore struct {
Expiration time.Duration
PreKey string
Context context.Context
Redis *redis.Redis
}
// UseWithCtx add context for captcha.
func (r *RedisStore) UseWithCtx(ctx context.Context) base64Captcha.Store {
r.Context = ctx
return r
}
// Set sets the captcha KV to redis.
func (r *RedisStore) Set(id string, value string) error {
err := r.Redis.Setex(r.PreKey+id, value, int(r.Expiration.Seconds()))
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 *RedisStore) Get(key string, clear bool) string {
val, err := r.Redis.Get(key)
if err != nil {
logx.Errorw("error occurs when captcha key gets from redis", logx.Field("detail", err))
return ""
}
if clear {
_, err := r.Redis.Del(key)
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 *RedisStore) Verify(id, answer string, clear bool) bool {
key := r.PreKey + id
v := r.Get(key, clear)
return v == answer
}
1
https://gitee.com/study-helper/common.git
git@gitee.com:study-helper/common.git
study-helper
common
common
v1.4.1

搜索帮助