Gin 中使用 base64Captcha 生成图形验证码

验证码库
https://github.com/mojocn/base64Captcha
中文文档
在models文件夹中写一个验证码的文件,Captcha.go
package models

import (
	"github.com/mojocn/base64Captcha"
	"image/color"
)

// 设置自带的 store 存在服务器内存中
var store = base64Captcha.DefaultMemStore

// GetCaptcha 获取验证码
func GetCaptcha() (string, string, error) {
	// 生成验证码
	var driver base64Captcha.Driver
	//driver = base64Captcha.NewDriverString(80, 240, 0, 0, 4, "1234567890", nil)
	//设置验证码的配置
	driverString := base64Captcha.DriverChinese{
		Height:          40,           //设置验证码图片的高度
		Width:           100,          //设置验证码图片的宽度
		NoiseCount:      0,            //设置干扰线的数量
		ShowLineOptions: 2 | 4,        //设置线条的类型
		Length:          4,            //设置验证码的长度
		Source:          "1234567890", //设置验证码的字符源
		BgColor: &color.RGBA{ //设置验证码图片的背景颜色
			R: 3,
			G: 102,
			B: 214,
			A: 125,
		},
		Fonts: []string{"wqy-microhei.ttc"}, //设置验证码的字体
	}

	//生成验证码
	driver = driverString.ConvertFonts()

	//生成base64图片
	c := base64Captcha.NewCaptcha(driver, store)
	//验证码id base64图片字符串 验证码字符串 error
	id, b64s, _, err := c.Generate()
	return id, b64s, err
}

// VerifyCaptcha 验证验证码
func VerifyCaptcha(id string, VerifyValue string) bool {
	//验证验证码,参数1是验证码的id,参数2是用户输入的验证码
	if store.Verify(id, VerifyValue, true) {
		return true
	} else {
		return false
	}
}

在登录控制器中添加获取验证码的方法,LoginController.go

package admin

import (
	"gin1/models"
	"github.com/gin-gonic/gin"
	"net/http"
)

type LoginController struct {}

func (con LoginController) Index(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/login/login.html", gin.H{})
}
func (con LoginController) DoLogin(c *gin.Context) {
	// 获取参数
	verifyValue := c.PostForm("verifyValue")
	captchaId := c.PostForm("captchaId")
	// 验证验证码
	if !models.VerifyCaptcha(captchaId, verifyValue) {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "验证码错误"})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "验证码正确"})
		return
	}

}

// GetCaptcha 获取验证码
func (con LoginController) GetCaptcha(c *gin.Context) {
	// 生成验证码,返回验证码id,base64图片字符串
	id, base64, err := models.GetCaptcha()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "验证码生成失败"})
		return
	}
	//定义一个map,用来存储验证码id和base64图片字符串
	data := make(map[string]interface{})
	data["id"] = id
	data["image"] = base64
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "验证码生成成功", "data": data})
}

设置路由,Admin.go

package routers

import (
	"gin1/controllers/admin"
	"gin1/middlewares"
	"github.com/gin-gonic/gin"
)

func AdminRoutersInit(r *gin.Engine) {
	//middlewares.InitMiddleware中间件
	adminRouters := r.Group("/admin", middlewares.Init)
	{
		//后台首页
		adminRouters.GET("/", admin.MainController{}.Index)
		//欢迎页
		adminRouters.GET("/welcome", admin.MainController{}.Welcome)
		//登录页
		adminRouters.GET("/login", admin.LoginController{}.Index)
		//登录操作
		adminRouters.POST("/doLogin", admin.LoginController{}.DoLogin)
		//获取验证码
		adminRouters.GET("/getCaptcha", admin.LoginController{}.GetCaptcha)

	}
}

登录页面,Login.html

{{ define "admin/login/login.html" }}

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>用户登录</title>
    <link rel="stylesheet" href="/static/admin/css/login.css">
    <script type="text/javascript" src="/static/admin/bootstrap/js/jquery-1.10.1.js"></script>
    <script type="text/javascript" src="/static/admin/js/login.js"></script>
</head>
<body>
<div class="container">
    <div id="login">
        <form action="/admin/doLogin" method="post" id="myform">
            <input type="hidden" name="captchaId" id="captchaId">
            <div class="l_title">小米商城后台管理系统-IT营</div>
            <dl>
                <dd>管理员姓名:<input class="text" type="text" name="username" id="username"></dd>
                <dd>管理员密码:<input class="text" type="password" name="password" id="password"></dd>
                <dd>验 证 码:<input id="verify" type="text" name="verifyValue">
                    <img id="captchaImg" src="">
                </dd>
                <dd><input type="submit" class="submit" name="dosubmit" value=""></dd>
            </dl>
        </form>
    </div>
</div>

</body>
</html>

{{end}}

登录页的js,login.js

$(function(){
    app.init();
})
var app={
    init:function(){
        this.getCaptcha()
        this.captchaImgChage()
    },
    getCaptcha:function(){
        $.get("/admin/getCaptcha?t="+Math.random(),function(response){
            console.log(response)
            $("#captchaId").val(response.data.id)
            $("#captchaImg").attr("src",response.data.image)
        })
    },
    captchaImgChage:function(){
        var that=this;
        $("#captchaImg").click(function(){
            that.getCaptcha()
        })
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值