Base64Captcha可以在服务端生成验证码,以base64的格式返回
为了能看到生成的base64验证码图片,我们借助gin
go get -u github.com/mojocn/base64Captcha
go get -u github.com/gin-gonic/gin
文档的示例看起来很复杂,下面,通过简单的一个小实例,来展示Base64Captcha的基本使用
项目示例
目录结构
main.go
captcha_util/captcha_util.go
templates/index.html
先写一个工具类,将base64Captcha
进行简单的封装,实现主要的功能:生成验证码
和验证验证码
package captcha_utilimport ("github.com/mojocn/base64Captcha"
)// 验证码工具类
type StringCaptcha struct {captcha *base64Captcha.Captcha
}// 创建验证码
func NewCaptcha() *StringCaptcha {// storestore := base64Captcha.DefaultMemStore// 包含数字和字母的字符集source := "123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"// driverdriver := base64Captcha.NewDriverString(80, // height int240, // width int6, // noiseCount int1, // showLineOptions int4, // length intsource, // source stringnil, // bgColor *color.RGBAnil, // fontsStorage FontsStoragenil, // fonts []string)captcha := base64Captcha.NewCaptcha(driver, store)return &StringCaptcha{captcha: captcha,}
}// 生成验证码
func (stringCaptcha *StringCaptcha) Generate() (string, string, string) {id, b64s, answer, _ := stringCaptcha.captcha.Generate()return id, b64s, answer
}// 验证验证码
func (stringCaptcha *StringCaptcha) Verify(id string, answer string) bool {return stringCaptcha.captcha.Verify(id, answer, true)
}
通过gin的两个路由,分别输出验证码
和验证验证码
package mainimport ("demo/captcha_util""fmt""html/template""net/http""github.com/gin-gonic/gin"
)func main() {app := gin.Default()// 加载模板文件app.LoadHTMLGlob("templates/*")// 验证码stringCaptcha := captcha_util.NewCaptcha()// 生成验证码app.GET("/generate", func(ctx *gin.Context) {id, b64s, answer := stringCaptcha.Generate()fmt.Println(answer)ctx.HTML(http.StatusOK, "index.html", gin.H{"captchaId": id,"b64s": template.URL(b64s),"answer": answer,})})// 验证app.POST("/verify", func(ctx *gin.Context) {answer := ctx.PostForm("answer")captchaId := ctx.PostForm("captchaId")result := stringCaptcha.Verify(captchaId, answer)ctx.JSON(http.StatusOK, gin.H{"captchaId": captchaId,"answer": answer,"result": result,})})// 监听并在 http://127.0.0.1:8080 上启动服务app.Run()
}
index.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Demo</title>
</head>
<body><img src="{{.b64s}}"><form action="/verify" method="post"><input type="text" name="captchaId" value="{{.captchaId}}" hidden><input type="text" name="answer" value=""><input type="submit" value="Submit"></form>
</body>
</html>
生成验证码页面,为了便于显示,直接用模板渲染的方式处理,也可已改为返回接口数据
http://localhost:8080/generate
提交验证码后返回验证结果
http://localhost:8080/verify
参考文章
- https://gin-gonic.com/zh-cn/docs/
- go使用template出现#ZgotmplZ
- https://pkg.go.dev/github.com/mojocn/base64Captcha