简介
github
文档
生成图形验证码
package mainimport ("github.com/gin-gonic/gin""github.com/mojocn/base64Captcha""net/http"
)var store = base64Captcha.DefaultMemStorefunc main() {r := gin.Default()group := r.Group("/captcha"){group.GET("/get", GetCaptcha)}r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}func GetCaptcha(c *gin.Context) {// height 高度 png 像素高度// width 宽度 png 像素高度// length 验证码默认位数// maxSkew 单个数字的最大绝对倾斜因子// dotCount 背景圆圈的数量driver := base64Captcha.NewDriverDigit(80, 240, 5, 0.7, 80)captcha := base64Captcha.NewCaptcha(driver, store)id, content, err := captcha.Generate()if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"msg": "生成验证码失败",})return}c.JSON(http.StatusOK, gin.H{"captchaId": id,"content": content,})
}
content就是文件内容,需要进行解码才能看到图片,点击解码
校验图片验证码
package mainimport ("github.com/gin-gonic/gin""github.com/mojocn/base64Captcha""net/http"
)var store = base64Captcha.DefaultMemStorefunc main() {r := gin.Default()group := r.Group("/captcha"){group.GET("/get", GetCaptcha)group.GET("/verify", CheckCapcha)}r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}func CheckCapcha(c *gin.Context) {id := c.DefaultQuery("captchaId", "")captchaVal := c.DefaultQuery("captchaVal", "")// id 验证码id// answer 需要校验的内容// clear 校验完是否清除res := store.Verify(id, captchaVal, true)c.JSON(http.StatusOK, gin.H{"data": res,})
}func GetCaptcha(c *gin.Context) {// height 高度 png 像素高度// width 宽度 png 像素高度// length 验证码默认位数// maxSkew 单个数字的最大绝对倾斜因子// dotCount 背景圆圈的数量driver := base64Captcha.NewDriverDigit(80, 240, 5, 0.7, 80)captcha := base64Captcha.NewCaptcha(driver, store)id, content, err := captcha.Generate()if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"msg": "生成验证码失败",})return}c.JSON(http.StatusOK, gin.H{"captchaId": id,"content": content,})
}
输入正确的验证码,就会返回true,二次验证或者输入错误的验证码都会返回false