golang包快速生成base64验证码

摘要:
Base64Captcha快速生成base64编码的图片验证代码串,支持多种样式,包括算术、数字、字母、混合模式和语音模式。Base64是用于在网络上传输8位字节码的最常见的编码方法之一。
base64Captcha快速生成base64编码图片验证码字符串

支持多种样式,算术,数字,字母,混合模式,语音模式.

Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一。Base64编码可用于在HTTP环境下传递较长的标识信息, 直接把base64当成是字符串方式的数据就好了
减少了http请求;数据就是图片;
为APIs微服务而设计

为什么base64图片 for RESTful 服务

  Data URIs 支持大部分浏览器,IE8之后也支持.
  小图片使用base64响应对于RESTful服务来说更便捷

godoc文档

在线Demo Playground Powered by Vuejs+elementUI+Axios

 
golang包快速生成base64验证码第1张
Playground

 
golang包快速生成base64验证码第2张
28+58=?.png

 
golang包快速生成base64验证码第3张
ACNRfd.png

 
golang包快速生成base64验证码第4张
rW4npZ.png

wav file

安装golang包

go get -u github.com/mojocn/base64Captcha

  

创建图像验证码

import "github.com/mojocn/base64Captcha"
func demoCodeCaptchaCreate() {
    //config struct for digits
    //数字验证码配置
    var configD = base64Captcha.ConfigDigit{
        Height:     80,
        Width:      240,
        MaxSkew:    0.7,
        DotCount:   80,
        CaptchaLen: 5,
    }
    //config struct for audio
    //声音验证码配置
    var configA = base64Captcha.ConfigAudio{
        CaptchaLen: 6,
        Language:   "zh",
    }
    //config struct for Character
    //字符,公式,验证码配置
    var configC = base64Captcha.ConfigCharacter{
        Height:             60,
        Width:              240,
        //const CaptchaModeNumber:数字,CaptchaModeAlphabet:字母,CaptchaModeArithmetic:算术,CaptchaModeNumberAlphabet:数字字母混合.
        Mode:               base64Captcha.CaptchaModeNumber,
        ComplexOfNoiseText: base64Captcha.CaptchaComplexLower,
        ComplexOfNoiseDot:  base64Captcha.CaptchaComplexLower,
        IsShowHollowLine:   false,
        IsShowNoiseDot:     false,
        IsShowNoiseText:    false,
        IsShowSlimeLine:    false,
        IsShowSineLine:     false,
        CaptchaLen:         6,
    }
    //create a audio captcha.
    idKeyA, capA := base64Captcha.GenerateCaptcha("", configA)
    //以base64编码
    base64stringA := base64Captcha.CaptchaWriteToBase64Encoding(capA)
    //create a characters captcha.
    idKeyC, capC := base64Captcha.GenerateCaptcha("", configC)
    //以base64编码
    base64stringC := base64Captcha.CaptchaWriteToBase64Encoding(capC)
    //create a digits captcha.
    idKeyD, capD := base64Captcha.GenerateCaptcha("", configD)
    //以base64编码
    base64stringD := base64Captcha.CaptchaWriteToBase64Encoding(capD)
    
    fmt.Println(idKeyA, base64stringA, "
")
    fmt.Println(idKeyC, base64stringC, "
")
    fmt.Println(idKeyD, base64stringD, "
")
}

  

验证图像验证码

import "github.com/mojocn/base64Captcha"
func verfiyCaptcha(idkey,verifyValue string){
    verifyResult := base64Captcha.VerifyCaptcha(idkey, verifyValue)
    if verifyResult {
        //success
    } else {
        //fail
    }
}

  

使用golang搭建API服务

// example of HTTP server that uses the captcha package.
package main

import (
    "encoding/json"
    "fmt"
    "github.com/mojocn/base64Captcha"
    "log"
    "net/http"
)

//ConfigJsonBody json request body.
type ConfigJsonBody struct {
    Id              string
    CaptchaType     string
    VerifyValue     string
    ConfigAudio     base64Captcha.ConfigAudio
    ConfigCharacter base64Captcha.ConfigCharacter
    ConfigDigit     base64Captcha.ConfigDigit
}

var configC = base64Captcha.ConfigCharacter{
    Height:             60,
    Width:              240,
    Mode:               0,
    ComplexOfNoiseText: 0,
    ComplexOfNoiseDot:  0,
    IsShowHollowLine:   false,
    IsShowNoiseDot:     false,
    IsShowNoiseText:    false,
    IsShowSlimeLine:    false,
    IsShowSineLine:     false,
    CaptchaLen:         6,
}


// base64Captcha create http handler
func generateCaptchaHandler(w http.ResponseWriter, r *http.Request) {
    //parse request parameters
    //接收客户端发送来的请求参数
    decoder := json.NewDecoder(r.Body)
    var postParameters ConfigJsonBody
    err := decoder.Decode(&postParameters)
    if err != nil {
        log.Println(err)
    }
    defer r.Body.Close()

    //create base64 encoding captcha
    //创建base64图像验证码

    var config interface{}
    switch postParameters.CaptchaType {
    case "audio":
        config = postParameters.ConfigAudio
    case "character":
        config = postParameters.ConfigCharacter
    default:
        config = postParameters.ConfigDigit
    }
    captchaId, digitCap := base64Captcha.GenerateCaptcha(postParameters.Id, config)
    base64Png := base64Captcha.CaptchaWriteToBase64Encoding(digitCap)

    //or you can do this
    //你也可以是用默认参数 生成图像验证码
    //base64Png := captcha.GenerateCaptchaPngBase64StringDefault(captchaId)

    //set json response
    //设置json响应

    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    body := map[string]interface{}{"code": 1, "data": base64Png, "captchaId": captchaId, "msg": "success"}
    json.NewEncoder(w).Encode(body)
}
// base64Captcha verify http handler
func captchaVerifyHandle(w http.ResponseWriter, r *http.Request) {

    //parse request parameters
    //接收客户端发送来的请求参数
    decoder := json.NewDecoder(r.Body)
    var postParameters ConfigJsonBody
    err := decoder.Decode(&postParameters)
    if err != nil {
        log.Println(err)
    }
    defer r.Body.Close()
    //verify the captcha
    //比较图像验证码
    verifyResult := base64Captcha.VerifyCaptcha(postParameters.Id, postParameters.VerifyValue)

    //set json response
    //设置json响应
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    body := map[string]interface{}{"code": "error", "data": "验证失败", "msg": "captcha failed"}
    if verifyResult {
        body = map[string]interface{}{"code": "success", "data": "验证通过", "msg": "captcha verified"}
    }
    json.NewEncoder(w).Encode(body)
}

//start a net/http server
//启动golang net/http 服务器
func main() {

    //serve Vuejs+ElementUI+Axios Web Application
    http.Handle("/", http.FileServer(http.Dir("./static")))

    //api for create captcha
    http.HandleFunc("/api/getCaptcha", generateCaptchaHandler)

    //api for verify captcha
    http.HandleFunc("/api/verifyCaptcha", captchaVerifyHandle)

    fmt.Println("Server is at localhost:3333")
    if err := http.ListenAndServe("localhost:3333", nil); err != nil {
        log.Fatal(err)
    }
}

  

运行demo代码

cd $GOPATH/src/github.com/mojocn/captcha/examples
go run main.go

访问 http://localhost:777

免责声明:文章转载自《golang包快速生成base64验证码》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇API性能测试基本性能指标及要求数据库粗浅了解下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Linux源码Kconfig文件语法分析

Kconfig是我们进行内核配置的关键文件,用于生成menuconfig的界面并生成最终确定编译选项的.config文件。关于Kconfig文件的编写规则,在Documentation/kbuild/kconfig-language.txt有详尽的叙述。这里主要用实例进行语法分析。 config 确定了条目前面是否有选项,menuconfig界面中的条目中...

weblogic 升级bsu_Weblogic补丁升级之坑坑洼洼

转至:https://blog.csdn.net/weixin_30682635/article/details/111911952 [概述] 虽然当前国内去IOE波涛汹涌,但不可否认OracleWeblogic当前市场还有有一定使用量。所以,weblogic依然是中间件运维的重要工作之一。然而Oracleweblogic已经连续三个季度(2019年10月...

base64的编码解码的一些坑

1、 //编码 value = base64encode(utf16to8(src)) //解码 value = utf8to16(base64decode(src))这里:base64编码之前先转成utf8,解码出来的也要从utf-8转为utf-16 2、base64编码分为字符串编码成字符串,字符串编码成数组,字符串解码成数组,字符串解码成字符串,等...

C#对config配置文件的管理

应用程序配置文件,对于asp.net是web.config,对于WINFORM程序是App.Config(ExeName.exe.config)。 配置文件,对于程序本身来说,就是基础和依据,其本质是一个xml文件,对于配置文件的操作,从.NET2.0开始,就非常方便了,提供了System[.Web].Configuration这个管理功能的NameSpa...

git 给远程库 添加多个url地址

 目录[-] 前提 使用流程 原理解析 注意 Other 参考文章 作者:shede333主页:http://my.oschina.net/shede333 && http://blog.sina.com.cn/u/1509658847版权声明:原创文章,版权声明:自由转载-非商用-非衍生-保持署名 | [Creative Commo...

centos7 离线源码安装 postgresql9.6.6

部署服务器时,数据库服务器是在局域网环境下,不对外公开访问,虽然能够通过ssh操作但是在安装应用软件时基本的yum安装并不能达到目的。也许可以下载rpm进行yum,但也许会死于依赖. 案例环境下载postgresql源码并解压新增postgres用户及用户组编译安装配置权限路径初始化数据库启动数据库 案例环境 一台可以公网访问的阿里云ECS --...