gofiber: 使用圖形驗證碼d

刘宏缔的架构森林發表於2024-12-07

一,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);
            }
        });
    }

三,測試效果:

gofiber: 使用圖形驗證碼d

相關文章