验证码项目
项目概述
这是一个基于 Gin 框架和 base64Captcha 库实现的验证码服务。
功能特性
- 生成数学运算验证码
- 验证用户输入的验证码
- 提供 RESTful API 接口
项目结构
go.mod - Go模块定义文件
go.sum - 依赖校验文件
main.go - 主程序入口
templates/
index.html - 前端页面模板
完整代码示例
后端代码 (main.go)
package main // 定义主包
import (
// 颜色处理包
"image/color"
"net/http" // HTTP协议支持
"github.com/gin-gonic/gin" // Gin Web框架
"github.com/mojocn/base64Captcha" // 验证码生成库
)
// 配置验证码驱动
// 使用默认的内存存储来保存验证码信息
var store = base64Captcha.DefaultMemStore // 默认存储(10240个容量,10分钟有效期)
func main() {
// 初始化Gin引擎
r := gin.Default()
// 加载模板文件
// 从templates目录加载所有HTML模板
r.LoadHTMLGlob("templates/*")
// 首页路由
// 处理GET请求,返回index.html模板
r.GET("/", func(c *gin.Context) {
// 渲染index.html模板
c.HTML(http.StatusOK, "index.html", nil)
})
// 获取验证码接口
// 处理获取验证码的GET请求
r.GET("/captcha", captchaMiddleware())
// 验证验证码接口
// 处理验证码验证的POST请求
r.POST("/verify", verifyCaptchaMiddleware())
// 启动服务
// 监听8080端口
r.Run(":8080")
}
// 验证码生成中间件
func captchaMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 创建算术验证码驱动
// 配置验证码参数:高度、宽度、干扰线等
driver := base64Captcha.NewDriverMath(
50, // 验证码图片高度
100, // 验证码图片宽度
2, // 干扰线数量
3, // 干扰线显示选项
&color.RGBA{R: 0, G: 0, B: 0, A: 0}, // 背景颜色(透明)
nil, // 字体存储
[]string{"wqy-microhei.ttc"}, // 使用的字体文件
)
// 创建验证码实例
captcha := base64Captcha.NewCaptcha(driver, store)
// 生成验证码
// 返回验证码ID、base64编码图片等
id, b64s, _, err := captcha.Generate()
if err != nil {
// 生成失败时返回错误信息
c.JSON(http.StatusInternalServerError, gin.H{"error": "生成验证码失败"})
return
}
// 返回验证码ID和base64编码的图片
// 客户端需要保存ID用于后续验证
c.JSON(http.StatusOK, gin.H{
"captcha_id": id, // 验证码唯一标识
"captcha_img": b64s, // base64编码的验证码图片
})
c.Next()
}
}
// 验证码检验中间件
func verifyCaptchaMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 定义请求结构体
var req struct {
CaptchaID string `json:"captcha_id"` // 验证码ID
CaptchaCode string `json:"captcha_code"` // 用户输入的验证码
}
// 绑定请求参数
// 将JSON请求体解析到req结构体
if err := c.ShouldBindJSON(&req); err != nil {
// 参数绑定失败时返回错误
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
return
}
// 验证验证码
// 检查验证码ID和用户输入是否匹配
if store.Verify(req.CaptchaID, req.CaptchaCode, true) {
// 验证成功
c.JSON(http.StatusOK, gin.H{"message": "验证码正确"})
} else {
// 验证失败
c.JSON(http.StatusBadRequest, gin.H{"error": "验证码错误"})
}
c.Next()
}
}
前端模板 (templates/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>验证码示例</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>验证码示例</h1>
<div>
<img id="captchaImg" style="border:1px solid #ddd" />
<button onclick="refreshCaptcha()">刷新验证码</button>
</div>
<div>
<input type="text" id="captchaInput" placeholder="请输入验证码" />
<button onclick="verifyCaptcha()">验证</button>
</div>
<script>
let currentCaptchaId = "";
// 刷新验证码
function refreshCaptcha() {
axios
.get("/captcha")
.then((response) => {
currentCaptchaId = response.data.captcha_id;
document.getElementById("captchaImg").src =
response.data.captcha_img;
})
.catch((error) => {
console.error("获取验证码失败:", error);
});
}
// 验证验证码
function verifyCaptcha() {
const code = document.getElementById("captchaInput").value;
if (!code) {
alert("请输入验证码");
return;
}
axios
.post("/verify", {
captcha_id: currentCaptchaId,
captcha_code: code,
})
.then((response) => {
alert(response.data.message);
})
.catch((error) => {
if (error.response) {
alert(error.response.data.error);
} else {
console.error("验证失败:", error);
}
});
}
// 页面加载时获取验证码
window.onload = refreshCaptcha;
</script>
</body>
</html>
API 接口
GET /captcha
- 获取验证码POST /verify
- 验证验证码
使用方法
- 启动服务:
go run main.go
- 访问
http://localhost:8080
- 调用 API 接口获取和验证验证码
依赖
- Go 1.16+
- Gin 框架
- base64Captcha 库