golang图片验证码

获取验证码

通过调用GetCaptcha函数,通过引用github.com/dchest/captcha库中的captcha.New()生成 id然后在获取图像的路径。

type CaptchaResponse struct {
	CaptchaId string
	ImageUrl  string
}

func GetCaptcha(c *gin.Context) {
	d := CaptchaResponse{
		CaptchaId: captcha.New(),
	}
	if d.CaptchaId != "" {
		d.ImageUrl = "/show/" + d.CaptchaId + ".png"
	} else {
		c.JSON(http.StatusInternalServerError, gin.H{"Message": "生成失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"Message": "生成成功",
		"Data":    d,
	})
}
func GetCaptchaPng(c *gin.Context) {
	source := c.Param("source")
	logrus.Info("GetCaptchaPng : " + source)
	recaptcha.ServeHTTP(c)
}

生成图片


func Serve(c *gin.Context, id, ext, lang string, download bool, width, height int) error {
	c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
	c.Header("Pragma", "no-cache")
	c.Header("Expires", "0")

	var content bytes.Buffer
	switch ext {
	case ".png":
		c.Header("Content-Type", "image/png")
		captcha.WriteImage(&content, id, width, height)
	case ".wav":
		c.Header("Content-Type", "audio/x-wav")
		captcha.WriteAudio(&content, id, lang)
	default:
		return captcha.ErrNotFound
	}

	if download {
		c.Header("Content-Type", "application/octet-stream")
	}
	c.Data(http.StatusOK, "application/octet-stream", content.Bytes())
	return nil
}

func ServeHTTP(c *gin.Context) {
	dir, file := path.Split(c.Request.URL.Path)
	ext := path.Ext(file)
	id := file[:len(file)-len(ext)]
	if ext == "" || id == "" {
		c.AbortWithStatus(http.StatusNotFound)
		return
	}
	fmt.Println("reload : " + c.Request.FormValue("reload"))
	if c.Request.FormValue("reload") != "" {
		captcha.Reload(id)
	}
	lang := strings.ToLower(c.Request.FormValue("lang"))
	download := path.Base(dir) == "download"
	if err := Serve(c, id, ext, lang, download, captcha.StdWidth, captcha.StdHeight); err == captcha.ErrNotFound {
		c.AbortWithStatus(http.StatusNotFound)
	}
}

进行比较

func VerifyCaptcha(c *gin.Context) {
	//baseResponse := model.NewBaseResponse()
	captchaId := c.PostForm("captchaId")
	value := c.PostForm("value")
	if captchaId == "" || value == "" {
		c.JSON(http.StatusBadRequest, gin.H{"Message": "输入为空错误"})
	} else {
		if captcha.VerifyString(captchaId, value) {
			c.JSON(http.StatusOK, gin.H{"Message": "验证成功"})
			return
		} else {
			c.JSON(http.StatusNotFound, gin.H{"messqge": "验证失败"})
		}
	}
}

结构图

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值