gofiber: 使用图形验证码d

一,go代码

1,安装第三方库:

$ go get -u github.com/mojocn/base64Captcha

2,service

package service

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

// 设置base64Captcha自带的store
var store = base64Captcha.DefaultMemStore

// 得到图形验证码
func CreateCapt() (id, b64s, answer string, err error) {
	var driver base64Captcha.Driver
	var driverString base64Captcha.DriverString

	// 配置验证码信息
	captchaConfig := base64Captcha.DriverString{
		Height:          150,
		Width:           380,
		NoiseCount:      0,
		ShowLineOptions: 2 | 4,
		Length:          4,
		Source:          "1234567890qwertyuioplkjhgfdsazxcvbnm",
		BgColor: &color.RGBA{
			R: 3,
			G: 102,
			B: 214,
			A: 125,
		},
		Fonts: []string{"wqy-microhei.ttc"},
	}
    //得到验证码
	driverString = captchaConfig
	driver = driverString.ConvertFonts()
	captcha := base64Captcha.NewCaptcha(driver, store)
	lid, lb64s, answer, lerr := captcha.Generate()
	return lid, lb64s, answer, lerr
}

//验证captcha是否正确
func CaptVerify(id string,capt string) bool {
	if store.Verify(id, capt, false) {
		return true
	} else {
		return false
	}
}

3,controller

func (tc *ToolsController) GetTheCaptcha(c *fiber.Ctx) error {
	id, b64s, answer, err := service.CreateCapt()
	if err != nil {
		return c.SendString("cha")
	}

	fmt.Println("id:",id)
	fmt.Println("answer:",answer)
	fmt.Println("b64s:",b64s)

	capt := CaptchaResult{
		Id:         id,
		Base64Blob: strings.Trim(b64s," "),
	}

	return c.Status(200).JSON(config.Success(capt))
}

验证代码:

	//验证码是否正确
	if service.CaptVerify(capt_id, code) == false {
		return c.Status(200).JSON(config.Error("验证码错误"))

	}

二,模板页面

1,

<img onclick="setcapt()" id="yzcodepic" class="yzcodepic" title="点击切换" src="">
<script language="JavaScript">

    var global_curCaptId = "{{.capt_id}}";
    var global_curBlob="{{.capt_blob}}";

    document.getElementById("yzcodepic").src=global_curBlob;

    function setcapt() {
        var url="/api/capt/getcaptcha"
        $.ajax({
            url: url,     // 指定请求的URL
            dataType: 'json', // 指定数据类型为JSON
            success: function(data) {
                // 请求成功后的回调函数
                console.log("成功");
                //更新图片
                global_curCaptId = data.data.id
                document.getElementById("yzcodepic").src=data.data.base_64_blob;
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("失败");
                // 请求失败后的回调函数
                console.error('Error: ' + textStatus + ' - ' + errorThrown);
            }
        });
    }

 

三,测试效果:

 

posted @ 2024-12-07 10:51  刘宏缔的架构森林  阅读(10)  评论(0编辑  收藏  举报