captcha
创建
go
id := captcha.New()go
id := captcha.NewLen(4)这是 id ,不是 value
生成图片
写入 http.ResponseWriter
go
w.Header().Set("Content-Type", "image/png")
captcha.WriteImage(w, id, 240, 80) // 宽、高写入 buffer
go
buf := make([]byte, 0, 1024)
captcha.WriteImage(&buf, id, 240, 80)设置
go
func init() {
// 过期时间(默认10分钟)
captcha.SetExpiration(600) // 秒
// 自定义默认长度
captcha.SetCustomLength(5)
}自定义存储
go
type Store interface {
Set(id string, digits []byte)
Get(id string, clear bool) (digits []byte)
Verify(id string, digits []byte, clear bool) bool
}go
type CaptchaStore struct {
client *RedisClient
ttl time.Duration
}
func (r *CaptchaStore) Set(id string, digits []byte) {
key := getCaptchaKey(id)
r.client.Set(context.Background(), key, digits, r.ttl)
}
func (r *CaptchaStore) Get(id string, clear bool) []byte {
key := getCaptchaKey(id)
ctx := context.Background()
val, err := r.client.Get(ctx, key)
if err != nil {
return []byte{}
}
if clear {
r.client.Del(ctx, key)
}
return []byte(val)
}
func (r *CaptchaStore) Verify(id string, digits string) bool {
return captcha.VerifyString(id, digits)
}