package CaptchaController import ( "bytes" "dsSdsf/Utils/RedisUtil" "fmt" ) //redis键值前缀 var prefix = "captcha_" //自定验证码的保存到redis,解决因集群负载均衡造成下一个请求无法访问的到的问题 var RedisStoreBean RedisStore //单例模式 type RedisStore struct { } func (_redis *RedisStore) Set(captchaId string, digits []byte) { //将captchaId和value值写入到redis,并且定义好过期时间,比如120秒 key := prefix + captchaId RedisUtil.SET(key, string(digits), 120) } func getValue(captchaId string) (digits []byte) { //通过capthcId从redis中读取value值 key := prefix + captchaId value, err := RedisUtil.GET(key) if err != nil { fmt.Println(err) return nil } else { return []byte(value) } } func (_redis *RedisStore) Get(captchaId string, clear bool) (digits []byte) { return getValue(captchaId) } func (_redis *RedisStore) VerifyString(captchaId string, value string) bool { key := prefix + captchaId digits := getValue(captchaId) //这段代码抄自captcha.go源码 ns := make([]byte, len(value), 8) for i := range ns { d := value[i] switch { case '0' <= d && d <= '9': ns[i] = d - '0' case d == ' ' || d == ',': // ignore default: return false } } //阅后即焚 RedisUtil.DEL(key) //返回两个字节数组的对比结果 isOk := bytes.Equal(digits, ns) return isOk }