验证码库
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()
})
}
}