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. 详解HTTP中GET与POST的区别,不是你看过的标准答案!

    防吐槽声明:本文适合程序员新人,自认阅文无数.技术超叼的大神不用看. GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就是GET把参数包含 ...

  2. 规则引擎drools的简单使用

    规则引擎适用于有复杂多变的规则,如商品满减.积分赠送.考勤规则等 一.引入maven依赖 <dependency> <groupId>org.drools</groupI ...

  3. php debug函数

    $debug=$_GET['debug'];//是说获取url中debug变量$debug=empty($debug)?'':$debug;//如果变量不为空,赋值为$debug,为空的话赋值 ''$ ...

  4. 参考MongoRepository,为接口生成bean实现注入

    首先弄个注解,给代码个入口,这个就是mongo的@EnableMongoRepositories了. @Target(ElementType.TYPE) @Retention(RetentionPol ...

  5. Qios RibbonForm QRibbonCaption添加qRibbonApplicationButton无法最大化问题

    winform 用了Qios DevSuite系列的控件. RibbonForm中QRibbonCaption添加qRibbonApplicationButton之后无法最大化. 修改qRibbonA ...

  6. Spark机器学习8· 文本处理(spark-shell)

    Spark机器学习 自然语言处理(NLP,Natural Language Processing) 提取特征 建模 机器学习 TF-IDF(词频 term frequency–逆向文件频率 inver ...

  7. .NET计时器的使用-Stopwatch类

    作用: 微软提供的常用于统计时间消耗的类,作为一个固定的API接口供大家使用. 先看代码: using System; using System.Collections.Generic; using ...

  8. JavaScript传递的是引用的副本

    看例子 var test1 = function (args) { args.name = "lcc2"; args = { name: "lcc3" }; } ...

  9. Linux:redhat6.5使用yum时提示需要注册问题解决方案

    Linux:redhat6.5使用yum时提示需要注册问题解决方案 一.问题 新安装了redhat6.5.安装后,登录系统,使用yum时候.提示: This system is not registe ...

  10. Spring中<ref local=""/>与<ref bean=""/>区别

    小 Spring中<ref local=""/>与<ref bean=""/>区别 (2011-03-19 19:21:58) 转载▼ ...