go 使用驗證碼庫
標籤(空格分隔): go
安裝
go get github.com/mojocn/base64Captcha
使用
package api
import (
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
"go.uber.org/zap"
"net/http"
)
var (
// 存儲方式
store = base64Captcha.DefaultMemStore
// 圖片高度
height = 40
// 圖片寬度
width = 240
// 干擾線選項
showLineOptions = 0 // 2 4 8
// 干擾數
noiseCount = 0
// 驗證碼長度
length = 4
// 字體
fonts = []string{"wqy-microhei.ttc"}
// 字符
stringSource = "1234567890QAZWSXCDERFVBGTYHNMJUIKLOP"
// 中文
chineseSource = "你,好,真,香,哈,哈,消,費,者,狗,仔,北京烤鴨"
// 音頻語言
language = "zh"
// 最大絕對偏斜係數爲個位數
maxSkew = 0
// 圓圈的數量
dotCount = 1
)
// GetCaptcha 獲取驗證碼
func GetCaptcha(ctx *gin.Context) {
id, b64s, err := CaptchaDigit()
if err != nil {
zap.S().Errorln("驗證碼獲取失敗:", err)
ctx.JSON(http.StatusBadRequest, gin.H{"msg": "驗證碼獲取失敗"})
return
}
ctx.JSON(http.StatusOK, gin.H{"msg": "success", "data": map[string]interface{}{
"id": id,
"captcha": b64s,
}})
return
}
// CheckCaptcha 驗證驗證碼
func CheckCaptcha(ctx *gin.Context) {
id := ctx.DefaultQuery("id", "")
value := ctx.DefaultQuery("value", "")
if id == "" || "" == value {
ctx.JSON(http.StatusBadRequest, gin.H{"msg": "參數不完整"})
return
}
b := CaptchaVerify(id, value)
if !b {
ctx.JSON(http.StatusBadRequest, gin.H{"msg": "驗證碼錯誤"})
return
}
ctx.JSON(http.StatusOK, gin.H{"msg": "success"})
return
}
// CaptchaString 生成字符串驗證碼
func CaptchaString() (id, b64s string, err error) {
// 字符串驗證碼
driver := &base64Captcha.DriverString{
Height: height,
Width: width,
ShowLineOptions: showLineOptions,
NoiseCount: noiseCount,
Source: stringSource,
Length: length,
Fonts: fonts,
}
driver = driver.ConvertFonts()
return base64Captcha.NewCaptcha(driver, store).Generate()
}
// CaptchaMath 生成算術驗證碼
func CaptchaMath() (id, b64s string, err error) {
driver := &base64Captcha.DriverMath{
Height: height,
Width: width,
NoiseCount: noiseCount,
ShowLineOptions: showLineOptions,
Fonts: fonts,
}
driver = driver.ConvertFonts()
return base64Captcha.NewCaptcha(driver, store).Generate()
}
// CaptchaChinese 生成中文驗證碼
func CaptchaChinese() (id, b64s string, err error) {
driver := &base64Captcha.DriverChinese{
Height: height,
Width: width,
NoiseCount: noiseCount,
ShowLineOptions: showLineOptions,
Length: length,
Source: chineseSource,
Fonts: []string{"wqy-microhei.ttc"},
}
driver = driver.ConvertFonts()
return base64Captcha.NewCaptcha(driver, store).Generate()
}
// CaptchaAudio 生成音頻驗證碼
func CaptchaAudio() (id, b64s string, err error) {
driver := &base64Captcha.DriverAudio{
Length: length,
// "en", "ja", "ru", "zh".
Language: language,
}
return base64Captcha.NewCaptcha(driver, store).Generate()
}
// CaptchaDigit 生成數字驗證碼
func CaptchaDigit() (id, b64s string, err error) {
driver := &base64Captcha.DriverDigit{
Height: height,
Width: width,
Length: length,
// 最大絕對偏斜係數爲個位數
MaxSkew: 0,
// 背景圓圈的數量。
DotCount: 0,
}
return base64Captcha.NewCaptcha(driver, store).Generate()
}
func CaptchaVerify(id, value string) bool {
return store.Verify(id, value, true)
}