图形验证码 captcha的使用
使用效果:
使用说明:
1、点击图片 或者 点击看不清 换一张,会自动更换。
2、输入错误,也会自动再更换一张。确保安全
验证码文件:common/captcha.go
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调用代码:
<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>
完结
但行好事,莫问前程!
本文来自博客园,作者:yangphp,转载请注明原文链接:https://www.cnblogs.com/ypeih/p/17334582.html