Gin base64Captcha 的使用案例

67 min read
package tool

import (
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"image/color"
)

// 定义验证码结果结构体
type CaptchaResult struct {
	Id           string `json:"id"`
	Base64Blob   string `json:"base_64_blob"`
	VertifyValue string `json:"code"`
}

// 生成图形验证码
func GenerateCaptcha(ctx *gin.Context) {
	// 配置验证码参数
	parameters := base64Captcha.ConfigCharacter{
		Height:             30, // 验证码图片高度
		Width:              60, // 验证码图片宽度
		ComplexOfNoiseText: 0,  // 文本噪声复杂度
		Mode:               3,  // 验证码模式:3表示使用字符模式,包括数字、大写字母和小写字母;1表示使用数字模式;2表示使用大写字母模式
		IsShowHollowLine:   false, // 是否显示空心线
		IsShowNoiseDot:     false, // 是否显示噪点
		IsShowNoiseText:    false, // 是否显示噪声文本
		IsShowSlimeLine:    false, // 是否显示粘滞性线条
		IsShowSineLine:     false, // 是否显示正弦线
		CaptchaLen:         4, // 验证码长度
		BgColor: &color.RGBA{ // 背景颜色
			R: 3,
			G: 102,
			B: 214,
			A: 254,
		},
	}

	// 生成验证码,传入空字符串作为ID,让库自动生成ID,传入配置参数parameters
	captchaId, captchaInterfaceInstance := base64Captcha.GenerateCaptcha("", parameters)
	// 将验证码转换为Base64编码
	base64blob := base64Captcha.CaptchaWriteToBase64Encoding(captchaInterfaceInstance)

	// 创建验证码结果对象
	captchaResult := CaptchaResult{Id: captchaId, Base64Blob: base64blob}

	// 返回成功响应
	Success(ctx, map[string]interface{}{
		"captcha_result": captchaResult,
	})

}

// 验证图形验证码
func VertifyCaptcha(id string, value string) bool {
	// 验证验证码
	vertifyResult := base64Captcha.VerifyCaptcha(id, value)
	return vertifyResult
}

通过SetCustomStore 自定义验证码相关信息的缓存对象

base64Captcha.SetCustomStore(&RediStore)

SetCusttomStore的参数类型如下:

type Store interface {
	Set(id string, value string)
	Get(id string, clear bool) string
}

自定义存储的实现如下:

package tool

import (
	"github.com/go-redis/redis"
	"github.com/mojocn/base64Captcha"
	"time"
	"log"
)

type RedisStore struct {
	client *redis.Client
}

var RediStore RedisStore

func InitRedisStore() *RedisStore {
	config := GetConfig().RedisConfig
	client := redis.NewClient(&redis.Options{
		Addr:     config.Addr + ":" + config.Port,
		Password: config.Password,
		DB:       config.Db,
	})

	RediStore = RedisStore{client: client}
	base64Captcha.SetCustomStore(&RediStore)

	return &RediStore
}

// set
func (rs *RedisStore) Set(id string, value string) {
	err := rs.client.Set(id, value, time.Minute*10).Err()
	if err != nil {
		log.Println(err)
	}
}

// get
func (rs *RedisStore) Get(id string, clear bool) string {
	val, err := rs.client.Get(id).Result()
	if err != nil {
		log.Println(err)
		return ""
	}
	if clear {
		err := rs.client.Del(id).Err()
		if err != nil {
			log.Println(err)
			return ""
		}
	}
	return val
}