package app import ( "simple-memo/utils" "github.com/gin-gonic/gin" "github.com/mojocn/base64Captcha" ) // CaptchaHandler 验证码接口定义 type CaptchaHandler interface { GenerateDigitCaptcha(c *gin.Context) // 生成数字验证码 VerifyDigitCaptcha(c *gin.Context) // 验证数字验证码 } type captchaHandler struct{} func NewCaptchaHandler() CaptchaHandler { return &captchaHandler{} } // 存储配置(使用内存存储,生产环境建议使用 Redis) var store = base64Captcha.DefaultMemStore // GenerateDigitCaptcha 生成数字验证码 func (h *captchaHandler) GenerateDigitCaptcha(c *gin.Context) { // 配置数字验证码参数 driver := base64Captcha.NewDriverDigit( 80, // 高度 240, // 宽度 4, // 验证码长度 0.7, // 干扰线概率 8, // 干扰线数量 ) captcha := base64Captcha.NewCaptcha(driver, store) id, b64s, err := captcha.Generate() if err != nil { utils.Fail(c, "生成验证码失败") return } utils.Ok(c, gin.H{ "captchaId": id, "image": b64s, }) } // VerifyDigitCaptcha 验证数字验证码 func (h *captchaHandler) VerifyDigitCaptcha(c *gin.Context) { var req struct { CaptchaId string `json:"captchaId" binding:"required"` Answer string `json:"answer" binding:"required"` } if err := c.ShouldBindJSON(&req); err != nil { utils.Fail(c, "参数错误") return } if store.Verify(req.CaptchaId, req.Answer, true) { utils.Ok(c, "验证通过") } else { utils.Fail(c, "验证码错误") } }