随心的博客

好记性不如个烂笔头,随心记录!

返回顶部

图形验证码 captcha的使用

使用效果:

 

 

使用说明:

1、点击图片 或者 点击看不清 换一张,会自动更换。

  2、输入错误,也会自动再更换一张。确保安全

 

验证码文件:common/captcha.go 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package common
 
import (
    "github.com/gin-gonic/gin"
    "github.com/go-playground/validator/v10"
    "github.com/mojocn/base64Captcha"
    "image/color"
    "net/http"
)
 
var store = base64Captcha.DefaultMemStore
// 获取验证码
func GetCaptcha(c *gin.Context) {
    //配置验证码
    driverString := base64Captcha.DriverString{
        Height:          60,
        Width:           200,
        NoiseCount:      0,     //噪点数
        ShowLineOptions: 2 | 4, //干扰线
        Length:          4,
        Source:          "123456789abcdefghijklmnopqrstuvwxwz",
        BgColor: &color.RGBA{
            R: 100,
            G: 100,
            B: 100,
            A: 100,
        },
        Fonts: []string{"wqy-microhei.ttc"},
    }
 
    var driver base64Captcha.Driver = driverString.ConvertFonts()
    //生成验证码
    cap := base64Captcha.NewCaptcha(driver, store)
    id, b64s, err := cap.Generate()
    body := map[string]interface{}{"code": 1, "data": b64s, "captchaId": id, "msg": "success"}
    if err != nil {
        body = map[string]interface{}{"code": 0, "msg": err.Error()}
    }
    c.JSON(http.StatusOK, body)
}
 
// 自定义验证码的验证器
func VerifyCaptcha(f validator.FieldLevel) bool {
    captcha := f.Parent().FieldByName("Captcha").Interface().(string)
    captcha_id := f.Parent().FieldByName("CaptchaId").Interface().(string)
 
    if store.Verify(captcha_id, captcha, true) {
        return true
    }
    return false
}

 

Html调用代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div class="row cl">
<div class="formControls col-xs-8 col-xs-offset-3">
<input name="captcha" id="captcha" class="input-text size-L" type="text" placeholder="验证码" onblur="if(this.value==''){this.value='验证码:'}" onclick="if(this.value=='验证码:'){this.value='';}" value="验证码:" style="width:150px;">
<img id="captcha_img" src="/admin/getCaptcha" onclick="showCaptcha()" style="width: 120px">
 <input type="hidden" name="captcha_id" id="captcha_id" />
<a id="kanbuq" href="javascript:showCaptcha();">看不清,换一张</a>
</div>
 </div>
 
 
<script type="text/javascript" src="/static/h-ui.lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" >
//显示验证码
    function showCaptcha(){
        $.get("/admin/getCaptcha",function (res){
            $("#captcha_img").attr("src",res.data)
            $("#captcha_id").val(res.captchaId)
 
        })
    }
showCaptcha()
</script>

  完结

posted @   yangphp  阅读(264)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示