使用base64Captcha库生成4位数字验证码并返回base64图像;2. 前端通过AJAX获取并展示验证码图片;3. 用户提交后,后端根据captcha_id和输入值调用store.Verify比对;4. 建议设置合理有效期、启用Redis存储并结合限流与CSRF防护。

在Golang开发Web应用时,表单验证码是防止机器人提交、保护接口安全的重要手段。实现一个完整的验证码验证流程,涉及生成验证码图像、存储验证码值、前端展示与用户提交后的比对校验。下面通过实际步骤详细说明如何在Golang中完成这一功能。
1. 生成图形验证码
使用开源库如 github.com/mojocn/base64Captcha 可以快速生成带干扰线的数字或字符验证码图片。该库支持音频和图像类型,这里以图像为例。
安装依赖:
go get github.com/mojocn/base74Captcha代码示例:生成一个4位数字验证码并返回base64编码图像
立即学习“go语言免费学习笔记(深入)”;
package mainimport (
"github.com/mojocn/base64Captcha"
"net/http"
)
var store = base64Captcha.DefaultMemStore
func generateCaptchaHandler(w http.ResponseWriter, r *http.Request) {
driver := &base64Captcha.DriverDigit{
Height: 80,
Width: 240,
Length: 4,
MaxSkew: 0.7,
DotCount: 80,
}
captcha := base64Captcha.NewCaptcha(driver, store)
id, b64s, err := captcha.Generate()
if err != nil {
http.Error(w, "生成失败", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"captcha_id":"` + id + `", "image":"` + b64s + `"}`))
}
2. 前端展示验证码
前端通过AJAX请求获取验证码ID和图像数据,并显示在页面上。
fetch("/captcha").then(res => res.json()).then(data => {document.getElementById("captcha-img").src = "data:image/png;base64," + data.image;
document.getElementById("captcha-id").value = data.captcha_id;
});
HTML部分:
3. 验证用户输入
当用户提交表单时,后端需要根据传入的 captcha_id 和用户输入的验证码进行比对。
func verifyCaptchaHandler(w http.ResponseWriter, r *http.Request) {r.ParseForm()
id := r.FormValue("captcha_id")
userInput := r.FormValue("user_captcha")
if !store.Verify(id, userInput, true) {
http.Error(w, "验证码错误", http.StatusBadRequest)
return
}
w.Write([]byte("验证成功"))
}
注意:store.Verify 第三个参数设为 true 表示一次性验证,成功后自动删除该验证码,防止重放攻击。
4. 安全与优化建议
- 验证码有效期不宜过长,memstore 默认为2分钟,可根据业务调整
- 避免在客户端暴露真实验证码明文
- 对频繁请求验证码的IP做限流处理
- 生产环境可替换为Redis存储验证码,实现分布式一致性
- 敏感操作(如登录、注册)应结合Token机制防止CSRF
基本上就这些。Golang通过简洁的API和高效内存管理,配合成熟库能快速构建安全的验证码系统。关键是保证生成、存储、验证三个环节的一致性和时效性,就能有效抵御自动化脚本攻击。










