获取验证码
通过调用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": "验证失败"})
}
}
}