使用base64Captcha生成数字验证码并返回Base64图像;2. 前端通过API获取并展示验证码图片;3. 用户提交后,后端根据ID验证输入是否正确;4. 验证码单次有效、区分大小写需注意、建议合理设置过期时间并避免日志泄露。

在Golang中实现Web表单验证码,核心是生成随机字符、保存验证码状态、展示图像以及验证用户输入。下面是一个实用且简洁的实现方式,使用标准库和第三方绘图库来完成。
使用 github.com/golang/freetype 或更简单的 github.com/mojocn/base64Captcha 可以快速生成图形验证码。这里推荐使用 base64Captcha,它支持数字、字符、音频等多种类型,并直接返回Base64编码图像,便于前端展示。
安装依赖:go get github.com/mojocn/base64Captcha
示例代码生成一个数字验证码:
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"encoding/json"
"net/http"
"github.com/mojocn/base64Captcha"
)
var store = base64Captcha.DefaultMemStore
func generateCaptchaHandler(w http.ResponseWriter, r *http.Request) {
// 配置验证码:4位数字
driver := base64Captcha.NewDriverDigit(80, 240, 4, 0.7, 80)
cp := base64Captcha.NewCaptcha(driver, store)
id, b64s, err := cp.Generate()
if err != nil {
http.Error(w, "生成失败", http.StatusInternalServerError)
return
}
// 返回JSON:包含ID和Base64图像
json.NewEncoder(w).Encode(map[string]string{
"captcha_id": id,
"captcha_image": b64s,
})
}
前端通过请求获取验证码数据,并将Base64图像显示在页面上:
fetch("/captcha")
.then(res => res.json())
.then(data => {
document.getElementById("captcha-img").src = "data:image/png;base64," + data.captcha_image;
document.getElementById("captcha-id").value = data.captcha_id;
});
HTML部分:
<img id="captcha-img" />
<input type="hidden" id="captcha-id" name="captcha_id"/>
<input type="text" name="captcha" placeholder="请输入验证码"/>
当用户提交表单时,后端根据传入的 captcha_id 和用户输入的值进行比对:
func verifyCaptchaHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
captchaID := r.FormValue("captcha_id")
userCaptcha := r.FormValue("captcha")
if !store.Verify(captchaID, userCaptcha, true) {
http.Error(w, "验证码错误", http.StatusBadRequest)
return
}
// 验证成功,继续处理表单
w.Write([]byte("验证通过"))
}
为了提升安全性,注意以下几点:
基本上就这些。用 base64Captcha 能快速集成,减少轮子开发,适合大多数表单防护场景。
以上就是如何在Golang中实现Web表单验证码的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号