golang使用base64Captcha做图形验证码并支持点击刷新

很多go的web框架都自带图形验证码,比如macaron和gin,但是这些验证码模块的验证码都比较弱,只能使用纯数字作为验证码,此处介绍base64Captcha包的使用方法并支持点击刷新。

  • 首先下载

    1
    go get "github.com/mojocn/base64Captcha"
  • 测试代码

    目录结构如下

    image-20220512134757796

    main.go

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    package main

    import (
    "html/template"
    "image/color"

    "github.com/go-macaron/session"
    "github.com/mojocn/base64Captcha"
    "gopkg.in/macaron.v1"
    )

    // 设置自带的 store(可以配置成redis)
    var store base64Captcha.Store

    func init() {
    store = base64Captcha.DefaultMemStore
    }

    //获取验证码
    func MakeCaptcha() (id, b64s string, err error) {
    var driver base64Captcha.Driver
    //配置验证码的参数
    driverString := base64Captcha.DriverString{
    Height: 60,
    Width: 120,
    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"},
    }
    //ConvertFonts 按名称加载字体
    driver = driverString.ConvertFonts()
    //创建 Captcha
    captcha := base64Captcha.NewCaptcha(driver, store)
    //Generate 生成随机 id、base64 图像字符串
    id, b64s, err = captcha.Generate()
    return id, b64s, err

    }

    //验证验证码
    func VerifyCaptcha(req macaron.Request) bool {
    _ = req.ParseForm()
    // true表示验证过后删除id信息
    return store.Verify(req.Form.Get("captcha_id"), req.Form.Get("captcha"), true)
    }

    type Captcha struct {
    Id string `json:"id"`
    ImageB64s string `json:"imageb64s"`
    }

    // 访问api
    func GetCaptcha(ctx *macaron.Context) {
    // Reload captcha.
    id, b64s, _ := MakeCaptcha()
    ctx.JSON(200, &Captcha{Id: id, ImageB64s: b64s})
    }

    func main() {
    m := macaron.Classic()
    m.Use(macaron.Renderer())
    //默认模版路径为temlplates
    m.Use(session.Sessioner())

    m.Get("/", func(ctx *macaron.Context) {
    id, b64s, _ := MakeCaptcha()
    ctx.Data["captcha_id"] = id
    // 这边要用template.URL否则无法正常渲染 base64当作url
    ctx.Data["base64_image"] = template.URL(b64s)
    ctx.HTML(200, "captcha")
    })

    m.Get("/captcha", GetCaptcha)

    m.Post("/", func(ctx *macaron.Context, flash *session.Flash) {
    if VerifyCaptcha(ctx.Req) {
    flash.Success("验证码输入正确")
    } else {
    flash.Success("验证码输入错误")
    }
    ctx.Redirect("/")
    })

    m.Run()
    }
  • 前端代码(模版)

    temlplates/captcha.html

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    <html>

    <body>
    <form action="/" method="post">
    <input class="form-control" placeholder="验证码" name="captcha" type="text">
    <input type="hidden" name="captcha_id" id="captcha_id" value="{{.captcha_id}}"><br><br>
    <img src="{{.base64_image}}" name="base64_image" id="base64_image" onclick="imageFlash()">
    <br><br>
    <input type="submit" value="提交">
    {{if .Flash.SuccessMsg}}
    <br><br>
    {{.Flash.SuccessMsg}}
    {{end}}
    </form>

    <script>
    function imageFlash(){
    //1.创建对象
    var xhr = new XMLHttpRequest();
    //2.指定服务器地址
    // false表示不异步,否则收不到信息
    xhr.open('GET','/captcha',false);
    //3.发送
    xhr.send();
    //4.接收服务器 cxlget3 ok
    if (xhr.responseText!=""){
    var info=xhr.responseText;
    var func=new Function("return"+info);
    var json=func();
    document.getElementById("captcha_id").value = json.id;
    document.getElementById("base64_image").src = json.imageb64s;
    }
    }
    </script>

    </body>
    </html>
  • 测试结果

    image-20220512135042832