Gin 中使用 base64Captcha 生成图形验证码
Gin 中使用 base64Captcha 生成图形验证 码以及分布式架构中配置 Captcha
https://github.com/mojocn/base64Captcha
captcha.mojotv.cn
package models
import (
"fmt"
"github.com/mojocn/base64Captcha"
"image/color"
)
// 设置自带的 store(可以配置成redis)
var store = base64Captcha.DefaultMemStore
//获取验证码
func MakeCaptcha() (id, b64s string, err error) {
var driver base64Captcha.Driver
//配置验证码的参数
driverString := base64Captcha.DriverString{
Height: 40,
Width: 100,
NoiseCount: 0,
ShowLineOptions: 2 | 4,
Length: 4,
Source: "1234567890qwertyuioplkjhgfdsazxcvbnm",
BgColor: &color.RGBA{R: 3, G: 102, B: 214, A: 125},
Fonts: []string{"wqy-microhei.ttc"},
}
//ConvertFonts 按名称加载字体
driver = driverString.ConvertFonts()
//创建 Captcha
captcha := base64Captcha.NewCaptcha(driver, store)
//Generate 生成随机 id、base64 图像字符串
id, b64s, err = captcha.Generate()
return id, b64s, err
}
//验证验证码
func VerifyCaptcha(id string, VerifyValue string) bool {
fmt.Println(id,VerifyValue )
if store.Verify(id, VerifyValue, true) {
//验证成功
return true
} else {
//验证失败
return false
}
}
中间件
func (con LoginController) DoLogin(c *gin.Context) {
//获取前端传过来的CaptchaId和verifyValue
captchId :=c.PostForm("captchaId")
verifyValue :=c.PostForm("verifyValue")
//排除前端提交的空请求
if captchId == "" || verifyValue == ""{
c.JSON(http.StatusOK, "验证码验证失败")
return
}
//调用验证验证码的方法
if flag:= models.VerifyCaptcha(captchId,verifyValue);flag==true{
//验证通过
fmt.Println(flag)
c.JSON(http.StatusOK, "验证码验证成功")
}else{
//验证失败
c.JSON(http.StatusOK, "验证码验证失败")
}
}