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

 
Playground
 
28+58=?.png
 
ACNRfd.png
 
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, "\n")
fmt.Println(idKeyC, base64stringC, "\n")
fmt.Println(idKeyD, base64stringD, "\n")
}

  

验证图像验证码

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验证码的更多相关文章

  1. 生成base64位图片验证码

    import org.springframework.util.Base64Utils; import javax.imageio.ImageIO; import java.awt.*; import ...

  2. python快速生成验证码

    利用python库random,string生成大小写字母和数字的随机验证码 import random import string def generate_code(bit_num): ''' : ...

  3. Golang 包了解以及程序的执行

    Golang 包了解以及程序的执行 引言  Go 语言是使用包来组织源代码的,包(package)是多个 Go 源码的集合,是一种高级的代码复用方案.Go 语言中为我们提供了很多内置包,如 fmt.o ...

  4. Myeclipse插件快速生成ssh项目并配置注解 在action层注入service的超详细过程

    最近发现,我对于ssh的 自动注入配置 还是不熟悉,于是整理了一下 终于做了一个 简单的 注入配置出来. 以前都是在applicationContext.xml 里面这样配 <bean id=& ...

  5. pillow实例 | 生成随机验证码

    1 PIL(Python Image Library) PIL是Python进行基本图片处理的package,囊括了诸如图片的剪裁.缩放.写入文字等功能.现在,我便以生成随机验证码为例,讲述PIL的基 ...

  6. golang包管理工具

    软件开发中,不可避免的会使用到第三方库,因此包管理工具可以极大的方便开发者管理第三方依赖,避免掉入"依赖地狱". 作为google强大背书的golang语言,golang官方包管理 ...

  7. Golang Module快速入门

    前言: 在Golang1.11之前的版本中,官方没有提供依赖和包管理工具.开发者通常会使用vendor或者glide的方式来管理依赖(也有直接使用GOPATH多环境方式),而在Golang1.11之后 ...

  8. python快速生成注释文档的方法

    python快速生成注释文档的方法 今天将告诉大家一个简单平时只要注意的小细节,就可以轻松生成注释文档,也可以检查我们写的类方法引用名称是否重复有问题等.一看别人专业的大牛们写的文档多牛多羡慕,不用担 ...

  9. Java生成BASE64编码

    1.所需jar包: BASE64Encoder.jar 2.在导包过程中,可能会出现工程不识别的情况.即:不能找到BASE64Encoder的jar包.此时,可以有两种方法解决这个问题: a.  只需 ...

随机推荐

  1. CNN学习笔记:卷积运算

    CNN学习笔记:卷积运算 边缘检测 卷积 卷积是一种有效提取图片特征的方法.一般用一个正方形卷积核,遍历图片上的每一个像素点.图片与卷积核重合区域内相对应的每一个像素值乘卷积核 .内相对应点的权重,然 ...

  2. REST API风格

    REST API风格 就是用URL定位资源,用HTTP描述操作. 看Url就知道要什么看http method就知道干什么看http status code就知道结果如何   主要是针对资源进行资源定 ...

  3. HDU4631(标程代码)

    /*将x从小到大排序,每次插入一个点,直接找比这个点的x大的第一个,然后从这个开始向两边找 ,找点的下标用多重容器实现*/ #include<stdio.h> #include<st ...

  4. FTP vsftp 安装、管理

    FTP简介 FTP是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为文传协议,用户Internet上的控制文件的双向传输. FTP的主要作用,就是让用户链接上一个远 ...

  5. 深入理解JVM3

    VM运行时数据区域 JVM执行Java程序的过程中,会使用到各种数据区域,这些区域有各自的用途.创建和销毁时间.根据<Java虚拟机规范(第二版)>的规定,JVM包括下列几个运行时数据区域 ...

  6. AMD C1E SUPPORT

    •C1E是一种电源管理状态,它可以让处理器节能不限于处理器内核.在CIE状态,可以通过降低内存时钟速度.关闭HT技术,来降低处理器能耗.这种新功能对于12核的处理器极其重要,因为这种处理器在设计上既增 ...

  7. spark学习12(Wordcount程序之spark-shell)

    在目录/home/hadoop/2016113012下有文件words.txt hello scala hello java hello python hello wujiadong 上传该文件到hd ...

  8. Node.js 项目的配置文件

    在 Node.js 中可以通过process.env来访问当前的环境变量信息,比如: { PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', T ...

  9. c语言字符处理函数常见使用集合

    1.最近看一些开源项目代码时,总会看到 c 语言中一些  "str" 开头的处理字符串的用法,有的之前没用到过,特此记录,随时看到随时添加. 这里不提出源码,只是一些使用说明加例子 ...

  10. 新东方雅思词汇---7.4、cap

    新东方雅思词汇---7.4.cap 一.总结 一句话总结: 抓住 capable 英 ['keɪpəb(ə)l]  美 ['kepəbl]  adj. 能干的,能胜任的:有才华的 词组短语 capab ...