go - base64数字验证码图片生成以及验证

使用 Go进阶37:重构我的base64Captcha图形验证码项目 | Go&Rust🦀 (mojotv.cn)

 

//下面两个是核心代码, 一个生成图片验证码,一个验证验证码是否正确,但是只能验证一次,因为他会清除验证id

//Generate generates a random id, base64 image string or an error if any
func (c *Captcha) Generate() (id, b64s string, err error) {
	id,content, answer := c.Driver.GenerateIdQuestionAnswer()
	item, err := c.Driver.DrawCaptcha(content)
	if err != nil {
		return "", "", err
	}
	c.Store.Set(id, answer)
	b64s = item.EncodeB64string()
	return
}
//if you has multiple captcha instances which shares a same store. You may want to use `store.Verify` method instead.
//Verify by given id key and remove the captcha value in store, return boolean value.
func (c *Captcha) Verify(id, answer string, clear bool) (match bool) {
	match = c.Store.Get(id, clear) == answer
	return
}

具体实现
var store = base64Captcha.DefaultMemStore

// GetCaptcha
// 获取验证码
func GetCaptcha(ctx *gin.Context) {

//指定数字图片验证码的格式 图片height 图片width 数字验证码的长度length maxSkew验证码倾斜程度
driver := base64Captcha.NewDriverDigit(80, 240, 5, 0.7, 80)
//拿到captcha对象
cp := base64Captcha.NewCaptcha(driver, store)
//使用cp的Generate方法生成验证码图片的id,以及图片的base64编码
id, b64s, err := cp.Generate()
if err != nil {
zap.S().Errorf("生成验证码错误", err.Error())
ctx.JSON(http.StatusInternalServerError, gin.H{
"msg": "生成验证码错误",
})
return
}

//如果验证码没错直接返回验证码图片的id和base64路径
ctx.JSON(http.StatusOK, gin.H{
"captchaId": id,
"picPath": b64s,
})
}


 
posted @   lunar-华仔  阅读(237)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示