第一步 下载第三方组件

go get -u github.com/mojocn/base64Captcha

下载过程中可能出错,主要原因还是go get golang.org/x/image 失败

解决方法:①cd $GOPATH/src/golang.org/x

② git clone https://github.com/golang/image

第二歩 设置CaptchaConfig类

type CaptchaConfig struct {

Id string

CaptchaType string

VerifyValue string

ConfigAudio base64Captcha.ConfigAudio

ConfigCharacter base64Captcha.ConfigCharacter

ConfigDigit base64Captcha.ConfigDigit

}

第三歩 创建CaptchaConfig类实例

var (

captchaConfig *CaptchaConfig

captchaConfigOnce sync.Once

)

// 获取base64验证码基本配置

func GetCaptchaConfig() *CaptchaConfig {

captchaConfigOnce.Do(func() {

captchaConfig = &CaptchaConfig{

Id: "",

CaptchaType: "character",

VerifyValue: "",

ConfigAudio: base64Captcha.ConfigAudio{},

ConfigCharacter: base64Captcha.ConfigCharacter{

Height: 60,

Width: 240,

Mode: 2,

IsUseSimpleFont: false,

ComplexOfNoiseText: 0,

ComplexOfNoiseDot: 0,

IsShowHollowLine: false,

IsShowNoiseDot: false,

IsShowNoiseText: false,

IsShowSlimeLine: false,

IsShowSineLine: false,

CaptchaLen: 0,

},

ConfigDigit: base64Captcha.ConfigDigit{},

}

})

return captchaConfig

}

第四歩 API部分

const (

CAPTCHA_IS_RIGHT = 0

CAPTCHA_IS_ERROR = -7

)

func GenerateCaptchaHandler(c *gin.Context) {

// get session

session := sessions.Default(c)

captchaConfig := util.GetCaptchaConfig()

//create base64 encoding captcha

//创建base64图像验证码

config := captchaConfig.ConfigCharacter

//GenerateCaptcha 第一个参数为空字符串,包会自动在服务器一个随机种子给你产生随机uiid.

captchaId, digitCap := base64Captcha.GenerateCaptcha(captchaConfig.Id, config)

base64Png := base64Captcha.CaptchaWriteToBase64Encoding(digitCap)

session.Set("captchaId", captchaId)

c.String(http.StatusOK, base64Png)

}

// 验证 验证码是否正确

// captchaId: 存于session中

// verifyValue: 客户端发来的验证码

func VerfiyCaptcha(captchaId, verifyValue string) (int, error){

verifyResult := base64Captcha.VerifyCaptcha(captchaId, verifyValue)

if verifyResult {

return CAPTCHA_IS_RIGHT,nil

} else {

return CAPTCHA_IS_ERROR, fmt.Errorf("captcha is error")

}

}

第五歩 简单介绍base64Captcha库的一些变量,参数

CaptchaModeNumber:数字,

CaptchaModeAlphabet:字母,

CaptchaModeArithmetic:算术,

CaptchaModeNumberAlphabet:数字字母混合.

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐