package CaptchaController import ( "dsSzxy/Utils/ConfigUtil" "fmt" "gitee.com/aesoper/cache" "gitee.com/aesoper/cache/redis" "gitee.com/aesoper/captchaStore" "github.com/gin-gonic/gin" "github.com/mojocn/base64Captcha" "image/color" "net/http" "time" ) // Routers 模块的路由配置 func Routers(r *gin.RouterGroup) { rr := r.Group("/captchaRelate") rr.GET("/getCaptcha", getCaptcha) rr.POST("/verifyCaptcha", verifyCaptcha) } // CaptchaResult 存储验证码的结构 type CaptchaResult struct { Id string `json:"id"` Base64Blob string `json:"base_64_blob"` } // GetOne 生成图形化验证码 func getCaptcha(c *gin.Context) { id, b64s := CaptMake() captchaResult := CaptchaResult{ Id: id, Base64Blob: b64s, } c.JSON(http.StatusOK, gin.H{"success": true, "captcha": captchaResult}) return } // Verify 验证captcha是否正确 func verifyCaptcha(c *gin.Context) { id := c.PostForm("id") capt := c.PostForm("capt") if id == "" || capt == "" { c.JSON(http.StatusOK, gin.H{"success": false, "msg": "参数错误!"}) } if CaptVerify(id, capt) == true { c.JSON(http.StatusOK, gin.H{"success": true}) } else { c.JSON(http.StatusOK, gin.H{"success": false}) } return } var store *captchaStore.CustomCaptchaStore // CaptMake 生成验证码 func CaptMake() (string, string) { // 生成默认数字 //driver := &base64Captcha.DriverDigit{ // Height: 100, // Width: 200, // Length: 4, // MaxSkew: 1, // DotCount: 2, //} //https://captcha.mojotv.cn/ //四则运算 driver := &base64Captcha.DriverMath{ Height: 60, Width: 240, NoiseCount: 0, BgColor: &color.RGBA{ R: 52, G: 56, B: 98, A: 58, }, Fonts: []string{"wqy-microhei.ttc"}, } driver.ConvertFonts() //中文 // 生成base64图片 c, err := cache.New(cache.Cfg{ Driver: "redis", Redis: redis.Options{ Addr: ConfigUtil.RedisIp + ":" + ConfigUtil.RedisPort, }, }) if err != nil { fmt.Println("初始化Redis服务器失败:", err) } store = captchaStore.NewCustomCaptchaStore(c, time.Minute*5, false) captcha := base64Captcha.NewCaptcha(driver, store) // 生成验证码base64字符串 id, b64s, err := captcha.Generate() if err != nil { fmt.Println("Register GetCaptchaPhoto get base64Captcha has err:", err) } return id, b64s } // CaptVerify 验证captcha是否正确 func CaptVerify(id string, capt string) bool { fmt.Println("id:" + id) fmt.Println("capt:" + capt) return store.Verify(id, capt, false) }