功能和驗證碼使用原理

- 本案例中沒有使用redis作為緩存,而是使用的內存存儲方法
github鏈接地址
- 下載命令
go get github.com/mojocn/base64Captcha
請求處理函數
// 生成圖片驗證碼
func (m *MemberController) captcha(context *gin.Context) {
// 生成圖片驗證碼,並返回給客戶端
tool.GenerateCaptcha(context)
}
// 校驗圖片驗證碼
func (m *MemberController) verifyCaptcha(context *gin.Context) {
var captchaResult tool.CaptchaResult
err := tool.Decode(context.Request.Body, &captchaResult) // 等價於:context.ShouldBind(&captchaResult)
if err != nil {
tool.Failed(context, "參數解析失敗")
}
// 獲取圖片驗證碼的id和b64s,並校驗
result := tool.VerifyCaptcha(captchaResult.Id, captchaResult.VerifyValue)
if result {
fmt.Println("圖片驗證碼校驗成功")
tool.Success(context, "校驗成功")
} else {
fmt.Println("圖片驗證碼校驗失敗")
tool.Failed(context, "校驗失敗")
}
}
package tool
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
)
type CaptchaResult struct {
Id string `json:"id"`
Base64Blog string `json:"base_64_blog"`
VerifyValue string `json:"code"`
}
// 默認存儲10240個驗證碼,每個驗證碼10分鍾過期
var store = base64Captcha.DefaultMemStore
// 生成圖片驗證碼
func GenerateCaptcha(context *gin.Context) {
// 生成默認數字
//driver := base64Captcha.DefaultDriverDigit
// 此尺寸的調整需要根據網站進行調試,鏈接:
// https://captcha.mojotv.cn/
driver := base64Captcha.NewDriverDigit(70, 130, 4, 0.8, 100)
// 生成base64圖片
captcha := base64Captcha.NewCaptcha(driver, store)
// 獲取
id, b64s, err := captcha.Generate()
if err != nil {
fmt.Println("Register GetCaptchaPhoto get base64Captcha has err:", err)
}
captchaResult := CaptchaResult{Id: id, Base64Blog: b64s}
Success(context, map[string]interface{}{
"captcha_result": captchaResult,
})
}
// 校驗圖片驗證碼,並清除內存空間
func VerifyCaptcha(id string, value string) bool {
// TODO 只要id存在,就會校驗並清除,無論校驗的值是否成功, 所以同一id只能校驗一次
// 注意:id,b64s是空 也會返回true 需要在加判斷
verifyResult := store.Verify(id, value, true)
return verifyResult
}
測試圖片鏈接
github鏈接
中文文檔