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

验证码库
https://github.com/mojocn/base64Captcha
中文文档
Go进阶37:重构我的base64Captcha图形验证码项目 | 🐶❤️🦀
在models文件夹中写一个验证码的文件,Captcha.go

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

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

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

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

javascript 复制代码
$(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()
        })
    }
}
相关推荐
小于负无穷4 天前
Go 中 Gin 框架的使用指南
开发语言·后端·golang·gin
落雨便归尘5 天前
go语言后端开发学习(七)——如何在gin框架中集成限流中间件
后端·学习·中间件·golang·gin
knoci8 天前
【Go】-基于Gin和GORM的小清单项目
开发语言·golang·gin
Boo_T8 天前
三十三、Gin的中间件
开发语言·后端·golang·gin
Boo_T8 天前
三十七、Gin完成登陆功能
开发语言·后端·golang·gin
揽月随风醉9 天前
Gin-封装自动路由
gin
Boo_T9 天前
三十五、Gin注册功能实战
开发语言·后端·golang·gin
好奇的菜鸟9 天前
Gin 自带日志系统:深入理解与自定义
gin
Boo_T9 天前
三十六、Gin注册功能-检查账号是否存在
开发语言·后端·golang·gin
knoci9 天前
【Go】-Gin框架
开发语言·后端·学习·golang·gin