依赖包

使用该方法实现图片验证码、必须先安装依赖的包,如果安装出错,请百度安装方法。
“github.com/mojocn/base64Captcha”

生成验证码、以及验证方法

验证图片验证码是否正确,只需要在验证的接口中调用VerfiyCaptcha方法即可。

import (
	"fmt"
	"github.com/mojocn/base64Captcha"
	"sync"
)

type CaptchaConfig struct {
	Id              string
	CaptchaType     string
	VerifyValue     string
	ConfigAudio     base64Captcha.ConfigAudio
	ConfigCharacter base64Captcha.ConfigCharacter
	ConfigDigit     base64Captcha.ConfigDigit
}

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:             48,
				Width:              120,
				Mode:               1,
				IsUseSimpleFont:    false,
				ComplexOfNoiseText: 0,
				ComplexOfNoiseDot:  0,
				IsShowHollowLine:   false,
				IsShowNoiseDot:     false,
				IsShowNoiseText:    false,
				IsShowSlimeLine:    false,
				IsShowSineLine:     false,
				CaptchaLen:         4,
			},
			ConfigDigit: base64Captcha.ConfigDigit{},
		}
	})
	return captchaConfig
}

//const (
//	CAPTCHA_IS_RIGHT = 0
//	CAPTCHA_IS_ERROR = -7
//)

//  验证 验证码是否正确
// captchaId: 存于session中
// verifyValue: 客户端发来的验证码
// 验证方法
func VerfiyCaptcha(captchaId, verifyValue string) error {
	verifyResult := base64Captcha.VerifyCaptcha(captchaId, verifyValue)
	if verifyResult {
		return nil
	} else {
		return fmt.Errorf("captcha is error")
	}
}