base64Captcha

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 30, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

README

一个灵活多样的验证码包

Test Ask DeepWiki Go Report Card GoDoc Build Status codecov stability-stable Foundation

Base64captcha 支持任何 Unicode 字符,并且可以轻松自定义以支持数学、中文、韩语、日语、俄语、阿拉伯语等。

1. 📖📖📖 文档与演示

2. 🚀🚀🚀 快速开始

2.1 🎬🎬🎬 使用历史版本

Tag v1.2.2

go get github.com/smart-unicom/[email protected]

或编辑你的 go.mod 文件为

github.com/smart-unicom/[email protected]

2.2 📥📥📥 下载包
go get -u github.com/smart-unicom/base64Captcha

大陆 Gopher 如果没有 VPN 导致 go get golang.org/x/image 失败的解决方案:

  • go version > 1.11
  • 设置环境变量 GOPROXY=https://goproxy.io
2.3 🏂🏂🏂 如何使用 base64Captcha 编程
2.3.1 🏇🏇🏇 实现 Store 接口 或使用内置内存存储
type Store interface {
	// Set 设置验证码 id 对应的值
	Set(id string, value string)

	// Get 返回验证码 id 对应的值。Clear 表示
	// 是否从存储中删除该验证码
	Get(id string, clear bool) string
	
    // 直接验证验证码答案
	Verify(id, answer string, clear bool) bool
}

2.3.2 🏄🏄🏄 实现 Driver 接口 或使用内置驱动程序

内置驱动程序包括:

  1. 内置数字驱动
  2. 内置字符串驱动
  3. 内置数学驱动
  4. 内置中文驱动
// Driver 验证码接口,供验证码引擎进行操作
	type Driver interface {
	//DrawCaptcha 绘制二进制项
	DrawCaptcha(content string) (item Item, err error)
	//GenerateIdQuestionAnswer 创建随机 id、内容和答案
	GenerateIdQuestionAnswer() (id, q, a string)
}
2.3.3 🚴🚴🚴 核心代码 captcha.go

captcha.go 是 base64Captcha 的入口,非常简单。

package base64Captcha

import (
	"math/rand"
	"time"
)

func init() {
	//初始化随机数种子
	rand.Seed(time.Now().UnixNano())
}

// Captcha 验证码基本信息
	type Captcha struct {
	Driver Driver
	Store  Store
}

//NewCaptcha 从驱动和存储创建一个验证码实例
func NewCaptcha(driver Driver, store Store) *Captcha {
	return &Captcha{Driver: driver, Store: store}
}

//Generate 生成一个随机 id、base64 图像字符串或错误
func (c *Captcha) Generate() (id, b64s string, err error) {
	id,content, answer := c.Driver.GenerateIdQuestionAnswer()
	item, err := c.Driver.DrawCaptcha(content)
	if err != nil {
		return "", "", err
	}
	c.Store.Set(id, answer)
	b64s = item.EncodeB64string()
	return
}

//通过给定的 id 键验证并从存储中删除验证码值,
//返回布尔值。
//如果多个验证码实例共享同一个存储。
//你可能想要调用 `store.Verify` 方法。
func (c *Captcha) Verify(id, answer string, clear bool) (match bool) {
	match = c.Store.Get(id, clear) == answer
	return
}

2.3.4 🚵🚵🚵 生成 Base64(图像/音频) 字符串
func (c *Captcha) Generate() (id, b64s string, err error) {
	id,content, answer := c.Driver.GenerateIdQuestionAnswer()
	item, err := c.Driver.DrawCaptcha(content)
	if err != nil {
		return "", "", err
	}
	c.Store.Set(id, answer)
	b64s = item.EncodeB64string()
	return
}
2.3.5 🤸🤸🤸 验证答案
//如果多个验证码实例共享同一个存储。你可能想使用 `store.Verify` 方法。
//通过给定的 id 键验证并从存储中删除验证码值,返回布尔值。
func (c *Captcha) Verify(id, answer string, clear bool) (match bool) {
	match = c.Store.Get(id, clear) == answer
	return
}
2.3.6 🏃🏃🏃 完整示例
// 使用验证码包的 HTTP 服务器示例
package main

import (
	"encoding/json"
	"fmt"
	"github.com/smart-unicom/base64Captcha"
	"log"
	"net/http"
)

//configJsonBody json 请求体
	type configJsonBody struct {
	Id            string
	CaptchaType   string
	VerifyValue   string
	DriverAudio   *base64Captcha.DriverAudio
	DriverString  *base64Captcha.DriverString
	DriverChinese *base64Captcha.DriverChinese
	DriverMath    *base64Captcha.DriverMath
	DriverDigit   *base64Captcha.DriverDigit
}

var store = base64Captcha.DefaultMemStore

// base64Captcha 创建 http 处理器
func generateCaptchaHandler(w http.ResponseWriter, r *http.Request) {
	//解析请求参数
	decoder := json.NewDecoder(r.Body)
	var param configJsonBody
	err := decoder.Decode(&param)
	if err != nil {
		log.Println(err)
	}
	defer r.Body.Close()
	var driver base64Captcha.Driver

	//创建 base64 编码的验证码
	switch param.CaptchaType {
	case "audio":
		driver = param.DriverAudio
	case "string":
		driver = param.DriverString.ConvertFonts()
	case "math":
		driver = param.DriverMath.ConvertFonts()
	case "chinese":
		driver = param.DriverChinese.ConvertFonts()
	default:
		driver = param.DriverDigit
	}
	c := base64Captcha.NewCaptcha(driver, store)
	id, b64s, err := c.Generate()
	body := map[string]interface{}{"code": 1, "data": b64s, "captchaId": id, "msg": "success"}
	if err != nil {
		body = map[string]interface{}{"code": 0, "msg": err.Error()}
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	json.NewEncoder(w).Encode(body)
}

// base64Captcha 验证 http 处理器
func captchaVerifyHandle(w http.ResponseWriter, r *http.Request) {

	//解析请求 json 体
	decoder := json.NewDecoder(r.Body)
	var param configJsonBody
	err := decoder.Decode(&param)
	if err != nil {
		log.Println(err)
	}
	defer r.Body.Close()
	//验证验证码
	body := map[string]interface{}{"code": 0, "msg": "failed"}
	if store.Verify(param.Id, param.VerifyValue, true) {
		body = map[string]interface{}{"code": 1, "msg": "ok"}
	}

	//设置 json 响应
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	json.NewEncoder(w).Encode(body)
}

//启动 net/http 服务器
func main() {
	//服务 Vuejs+ElementUI+Axios Web 应用
	http.Handle("/", http.FileServer(http.Dir("./static")))

	//创建验证码的 api
	http.HandleFunc("/api/getCaptcha", generateCaptchaHandler)

	//验证验证码的 api
	http.HandleFunc("/api/verifyCaptcha", captchaVerifyHandle)

	fmt.Println("服务器运行在 :8777")
	if err := http.ListenAndServe(":8777", nil); err != nil {
		log.Fatal(err)
	}
}
2.3.7 使用 Redis 作为存储示例
package main

import (
	"encoding/json"
	"fmt"
	"github.com/smart-unicom/base64Captcha"
	"log"
	"net/http"
	"time"
)

//configJsonBody json 请求体
	type configJsonBody struct {
	Id            string
	CaptchaType   string
	VerifyValue   string
	DriverAudio   *base64Captcha.DriverAudio
	DriverString  *base64Captcha.DriverString
	DriverChinese *base64Captcha.DriverChinese
	DriverMath    *base64Captcha.DriverMath
	DriverDigit   *base64Captcha.DriverDigit
}

// 创建 Redis 存储实例
func init() {
	// Redis 配置
	config := base64Captcha.RedisConfig{
		Addr:       "localhost:6379",  // Redis 地址
		Password:   "",               // Redis 密码
		DB:         0,                // Redis 数据库索引
		KeyPrefix:  "captcha:",       // Redis 键前缀
		Expiration: 10 * time.Minute, // 验证码过期时间
	}

	// 创建 Redis 存储
	store = base64Captcha.NewStoreRedis(config)
}

var store *base64Captcha.StoreRedis

// base64Captcha 创建 http 处理器
func generateCaptchaHandler(w http.ResponseWriter, r *http.Request) {
	//解析请求参数
	decoder := json.NewDecoder(r.Body)
	var param configJsonBody
	err := decoder.Decode(&param)
	if err != nil {
		log.Println(err)
	}
	defer r.Body.Close()
	var driver base64Captcha.Driver

	//创建 base64 编码的验证码
	switch param.CaptchaType {
	case "audio":
		driver = param.DriverAudio
	case "string":
		driver = param.DriverString.ConvertFonts()
	case "math":
		driver = param.DriverMath.ConvertFonts()
	case "chinese":
		driver = param.DriverChinese.ConvertFonts()
	default:
		driver = param.DriverDigit
	}
	c := base64Captcha.NewCaptcha(driver, store)
	id, b64s, err := c.Generate()
	body := map[string]interface{}{"code": 1, "data": b64s, "captchaId": id, "msg": "success"}
	if err != nil {
		body = map[string]interface{}{"code": 0, "msg": err.Error()}
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	json.NewEncoder(w).Encode(body)
}

// base64Captcha 验证 http 处理器
func captchaVerifyHandle(w http.ResponseWriter, r *http.Request) {

	//解析请求 json 体
	decoder := json.NewDecoder(r.Body)
	var param configJsonBody
	err := decoder.Decode(&param)
	if err != nil {
		log.Println(err)
	}
	defer r.Body.Close()
	//验证验证码
	body := map[string]interface{}{"code": 0, "msg": "failed"}
	if store.Verify(param.Id, param.VerifyValue, true) {
		body = map[string]interface{}{"code": 1, "msg": "ok"}
	}

	//设置 json 响应
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	json.NewEncoder(w).Encode(body)
}

//启动 net/http 服务器
func main() {
	//服务 Vuejs+ElementUI+Axios Web 应用
	http.Handle("/", http.FileServer(http.Dir("./static")))

	//创建验证码的 api
	http.HandleFunc("/api/getCaptcha", generateCaptchaHandler)

	//验证验证码的 api
	http.HandleFunc("/api/verifyCaptcha", captchaVerifyHandle)

	fmt.Println("服务器运行在 :8777")
	if err := http.ListenAndServe(":8777", nil); err != nil {
		log.Fatal(err)
	}
}
2.3.8 使用 Etcd 作为存储示例

captcha with etcd database as store

3. 🎨🎨🎨 自定义

你可以通过实现 接口驱动接口项目 来自定义验证码显示图像。

以下是一些参考示例:

  1. DriverMath
  2. DriverChinese
  3. ItemChar

你甚至可以根据自己的喜好设计 captcha 结构

4. 💖💖💖 感谢

5. 🍭🍭🍭 许可证

base64Captcha 源代码根据 Apache 许可证第 2 版授权 (http://www.apache.org/licenses/LICENSE-2.0.html).

Documentation

Overview

Package base64Captcha 验证码包 支持数字、字母、算术、音频和数字字母混合验证码 用于快速开发Go语言的RESTful API、Web应用和后端服务 给定一个字符串标识符,返回base64编码的PNG图片字符串

Index

Constants

View Source
const (

	// TxtNumbers 数字字符集
	TxtNumbers = "012346789"
	// TxtAlphabet 字母字符集
	TxtAlphabet = "ABCDEFGHJKMNOQRSTUVXYZabcdefghjkmnoqrstuvxyz"
	// TxtSimpleCharaters 简单的数字和字母字符集
	TxtSimpleCharaters = "13467ertyiadfhjkxcvbnERTYADFGHJKXCVBN"
	// TxtChineseCharaters 中文汉字字符集
	TxtChineseCharaters = "的一是在不了有和人这中大为上个国我以要他" +
		"时来用们生到作地于出就分对成会可主发年动" +
		"同工也能下过子说产种面而方后多定行学法所" +
		"民得经十三之进着等部度家电力里如水化高自" +
		"二理起小物现实加量都两体制机当使点从业本" +
		"去把性好应开它合还因由其些然前外天政四日" +
		"那社义事平形相全表间样与关各重新线内数正" +
		"心反你明看原又么利比或但质气第向道命此变" +
		"条只没结解问意建月公无系军很情者最立代想" +
		"已通并提直题党程展五果料象员革位入常文总" +
		"次品式活设及管特件长求老头基资边流路级少" +
		"图山统接知较将组见计别她手角期根论运农指" +
		"几九区强放决西被干做必战先回则任取据处队" +
		"南给色光门即保治北造百规热领七海口东导器" +
		"压志世金增争济阶油思术极交受联什认六共权" +
		"收证改清己美再采转更单风切打白教速花带安" +
		"场身车例真务具万每目至达走积示议声报斗完" +
		"类八离华名确才科张信马节话米整空元况今集" +
		"温传土许步群广石记需段研界拉林律叫且究观" +
		"越织装影算低持音众书布复容儿须际商非验连" +
		"断深难近矿千周委素技备半办青省列习响约支" +
		"般史感劳便团往酸历市克何除消构府称太准精" +
		"值号率族维划选标写存候毛亲快效斯院查江型" +
		"眼王按格养易置派层片始却专状育厂京识适属" +
		"圆包火住调满县局照参红细引听该铁价严龙飞"

	// MimeTypeAudio 音频验证码的base64 MIME类型
	MimeTypeAudio = "audio/wav"
	// MimeTypeImage 图片验证码的base64 MIME类型
	MimeTypeImage = "image/png"
	// Emoji 表情符号字符集
	Emoji = "" /* 268-byte string literal not displayed */
)
View Source
const (
	// OptionShowHollowLine 显示空心线选项
	OptionShowHollowLine = 2
	// OptionShowSlimeLine 显示细线选项
	OptionShowSlimeLine = 4
	// OptionShowSineLine 显示正弦曲线选项
	OptionShowSineLine = 8
)

Variables

View Source
var (
	// GCLimitNumber 默认存储触发垃圾回收的验证码数量阈值
	GCLimitNumber = 10240
	// Expiration 默认存储的验证码过期时间
	Expiration = 10 * time.Minute
	// DefaultMemStore 默认的共享验证码存储实例
	DefaultMemStore = NewMemoryStore(GCLimitNumber, Expiration)
)
View Source
var DefaultDriverAudio = NewDriverAudio(6, "en")

DefaultDriverAudio is a default audio driver

View Source
var DefaultDriverDigit = NewDriverDigit(80, 240, 5, 0.7, 80)

DefaultDriverDigit is a default driver of digit

View Source
var DefaultEmbeddedFonts = NewEmbeddedFontsStorage(defaultEmbeddedFontsFS)

Functions

func RandColor

func RandColor() color.RGBA

RandColor get random color. 生成随机颜色.

func RandDeepColor

func RandDeepColor() color.RGBA

RandDeepColor get random deep color. 随机生成深色系.

func RandLightColor

func RandLightColor() color.RGBA

RandLightColor get random ligth color. 随机生成浅色.

func RandText

func RandText(size int, sourceChars string) string

RandText creates random text of given size.

func RandomId

func RandomId() string

RandomId returns a new random id key string.

Types

type Captcha

type Captcha struct {
	Driver Driver // 验证码驱动
	Store  Store  // 存储后端
}

Captcha 验证码基本信息结构体

func NewCaptcha

func NewCaptcha(driver Driver, store Store) *Captcha

NewCaptcha 创建验证码实例 driver: 验证码驱动(数字、字符串、数学等) store: 存储后端(内存、Redis等)

func (*Captcha) Generate

func (c *Captcha) Generate() (id, b64s, answer string, err error)

Generate 生成验证码 返回:验证码ID、base64编码的图片字符串、答案、错误

func (*Captcha) Verify

func (c *Captcha) Verify(id, answer string, clear bool) (match bool)

Verify 验证验证码 id: 验证码ID answer: 用户输入的答案 clear: 验证后是否清除存储的验证码 返回:是否匹配 如果有多个验证码实例共享同一个存储,建议直接调用 store.Verify 方法

type Driver

type Driver interface {
	// DrawCaptcha 绘制验证码图像/音频
	DrawCaptcha(content string) (item Item, err error)
	// GenerateIdQuestionAnswer 生成随机的验证码ID、问题内容和答案
	GenerateIdQuestionAnswer() (id, q, a string)
}

Driver 验证码驱动接口 用于验证码引擎生成验证码内容

type DriverAudio

type DriverAudio struct {
	// Length Default number of digits in captcha solution.
	Length int
	// Language possible values for lang are "en", "ja", "ru", "zh".
	Language string
}

DriverAudio captcha config for captcha-engine-audio.

func NewDriverAudio

func NewDriverAudio(length int, language string) *DriverAudio

NewDriverAudio creates a driver of audio

func (*DriverAudio) DrawCaptcha

func (d *DriverAudio) DrawCaptcha(content string) (item Item, err error)

DrawCaptcha creates audio captcha item

func (*DriverAudio) GenerateIdQuestionAnswer

func (d *DriverAudio) GenerateIdQuestionAnswer() (id, q, a string)

GenerateIdQuestionAnswer creates id,captcha content and answer

type DriverChinese

type DriverChinese struct {
	//Height png height in pixel.
	Height int
	//Width Captcha png width in pixel.
	Width int

	//NoiseCount text noise count.
	NoiseCount int

	//ShowLineOptions := OptionShowHollowLine | OptionShowSlimeLine | OptionShowSineLine .
	ShowLineOptions int

	//Length random string length.
	Length int

	//Source is a unicode which is the rand string from.
	Source string

	//BgColor captcha image background color (optional)
	BgColor *color.RGBA

	//Fonts loads by name see fonts.go's comment
	Fonts []string
	// contains filtered or unexported fields
}

DriverChinese is a driver of unicode Chinese characters.

func NewDriverChinese

func NewDriverChinese(height int, width int, noiseCount int, showLineOptions int, length int, source string, bgColor *color.RGBA, fontsStorage FontsStorage, fonts []string) *DriverChinese

NewDriverChinese creates a driver of Chinese characters

func (*DriverChinese) ConvertFonts

func (d *DriverChinese) ConvertFonts() *DriverChinese

ConvertFonts loads fonts by names

func (*DriverChinese) DrawCaptcha

func (d *DriverChinese) DrawCaptcha(content string) (item Item, err error)

DrawCaptcha generates captcha item(image)

func (*DriverChinese) GenerateIdQuestionAnswer

func (d *DriverChinese) GenerateIdQuestionAnswer() (id, content, answer string)

GenerateIdQuestionAnswer generates captcha content and its answer

type DriverDigit

type DriverDigit struct {
	// Height png height in pixel.
	Height int
	// Width Captcha png width in pixel.
	Width int
	// DefaultLen Default number of digits in captcha solution.
	Length int
	// MaxSkew max absolute skew factor of a single digit.
	MaxSkew float64
	// DotCount Number of background circles.
	DotCount int
}

DriverDigit config for captcha-engine-digit.

func NewDriverDigit

func NewDriverDigit(height int, width int, length int, maxSkew float64, dotCount int) *DriverDigit

NewDriverDigit creates a driver of digit

func (*DriverDigit) DrawCaptcha

func (d *DriverDigit) DrawCaptcha(content string) (item Item, err error)

DrawCaptcha creates digit captcha item

func (*DriverDigit) GenerateIdQuestionAnswer

func (d *DriverDigit) GenerateIdQuestionAnswer() (id, q, a string)

GenerateIdQuestionAnswer creates captcha content and answer

func (*DriverDigit) GenerateSpecificIdQuestionAnswer

func (d *DriverDigit) GenerateSpecificIdQuestionAnswer(mId string) (id, q, a string)

GenerateIdQuestionAnswer creates captcha content and answer

type DriverLanguage

type DriverLanguage struct {
	// Height png height in pixel.
	Height int
	// Width Captcha png width in pixel.
	Width int

	//NoiseCount text noise count.
	NoiseCount int

	//ShowLineOptions := OptionShowHollowLine | OptionShowSlimeLine | OptionShowSineLine .
	ShowLineOptions int

	//Length random string length.
	Length int

	//BgColor captcha image background color (optional)
	BgColor *color.RGBA

	//Fonts loads by name see fonts.go's comment
	Fonts        []*truetype.Font
	LanguageCode string
	// contains filtered or unexported fields
}

DriverLanguage generates language unicode by lanuage

func NewDriverLanguage

func NewDriverLanguage(height int, width int, noiseCount int, showLineOptions int, length int, bgColor *color.RGBA, fontsStorage FontsStorage, fonts []*truetype.Font, languageCode string) *DriverLanguage

NewDriverLanguage creates a driver

func (*DriverLanguage) DrawCaptcha

func (d *DriverLanguage) DrawCaptcha(content string) (item Item, err error)

DrawCaptcha creates item

func (*DriverLanguage) GenerateIdQuestionAnswer

func (d *DriverLanguage) GenerateIdQuestionAnswer() (id, content, answer string)

GenerateIdQuestionAnswer creates content and answer

type DriverMath

type DriverMath struct {
	//Height png height in pixel.
	Height int

	// Width Captcha png width in pixel.
	Width int

	//NoiseCount text noise count.
	NoiseCount int

	//ShowLineOptions := OptionShowHollowLine | OptionShowSlimeLine | OptionShowSineLine .
	ShowLineOptions int

	//BgColor captcha image background color (optional)
	BgColor *color.RGBA

	//Fonts loads by name see fonts.go's comment
	Fonts []string
	// contains filtered or unexported fields
}

DriverMath captcha config for captcha math

func NewDriverMath

func NewDriverMath(height int, width int, noiseCount int, showLineOptions int, bgColor *color.RGBA, fontsStorage FontsStorage, fonts []string) *DriverMath

NewDriverMath creates a driver of math

func (*DriverMath) ConvertFonts

func (d *DriverMath) ConvertFonts() *DriverMath

ConvertFonts loads fonts from names

func (*DriverMath) DrawCaptcha

func (d *DriverMath) DrawCaptcha(question string) (item Item, err error)

DrawCaptcha creates math captcha item

func (*DriverMath) GenerateIdQuestionAnswer

func (d *DriverMath) GenerateIdQuestionAnswer() (id, question, answer string)

GenerateIdQuestionAnswer creates id,captcha content and answer

type DriverString

type DriverString struct {
	// Height png height in pixel.
	Height int

	// Width Captcha png width in pixel.
	Width int

	//NoiseCount text noise count.
	NoiseCount int

	//ShowLineOptions := OptionShowHollowLine | OptionShowSlimeLine | OptionShowSineLine .
	ShowLineOptions int

	//Length random string length.
	Length int

	//Source is a unicode which is the rand string from.
	Source string

	//BgColor captcha image background color (optional)
	BgColor *color.RGBA

	//Fonts loads by name see fonts.go's comment
	Fonts []string
	// contains filtered or unexported fields
}

DriverString captcha config for captcha-engine-characters.

func NewDriverString

func NewDriverString(height int, width int, noiseCount int, showLineOptions int, length int, source string, bgColor *color.RGBA, fontsStorage FontsStorage, fonts []string) *DriverString

NewDriverString creates driver

func (*DriverString) ConvertFonts

func (d *DriverString) ConvertFonts() *DriverString

ConvertFonts loads fonts by names

func (*DriverString) DrawCaptcha

func (d *DriverString) DrawCaptcha(content string) (item Item, err error)

DrawCaptcha draws captcha item

func (*DriverString) GenerateIdQuestionAnswer

func (d *DriverString) GenerateIdQuestionAnswer() (id, content, answer string)

GenerateIdQuestionAnswer creates id,content and answer

type EmbeddedFontsStorage

type EmbeddedFontsStorage struct {
	// contains filtered or unexported fields
}

func NewEmbeddedFontsStorage

func NewEmbeddedFontsStorage(fs embed.FS) *EmbeddedFontsStorage

func (*EmbeddedFontsStorage) LoadFontByName

func (s *EmbeddedFontsStorage) LoadFontByName(name string) *truetype.Font

func (*EmbeddedFontsStorage) LoadFontsByNames

func (s *EmbeddedFontsStorage) LoadFontsByNames(assetFontNames []string) []*truetype.Font

LoadFontsByNames import fonts from dir. make the simple-font(RitaSmith.ttf) the first font of trueTypeFonts.

type FontsStorage

type FontsStorage interface {
	// LoadFontByName returns the font from the storage
	LoadFontByName(name string) *truetype.Font

	// LoadFontsByNames returns multiple fonts from storage
	LoadFontsByNames(assetFontNames []string) []*truetype.Font
}

FontsStorage interface for working with fonts

type Item

type Item interface {
	//WriteTo writes to a writer
	WriteTo(w io.Writer) (n int64, err error)
	//EncodeB64string encodes as base64 string
	EncodeB64string() string
}

Item is captcha item interface

type ItemAudio

type ItemAudio struct {
	// contains filtered or unexported fields
}

ItemAudio captcha-audio-engine return type.

func (*ItemAudio) EncodeB64string

func (a *ItemAudio) EncodeB64string() string

EncodeB64string encodes a sound to base64 string

func (*ItemAudio) WriteTo

func (a *ItemAudio) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes captcha audio in WAVE format into the given io.Writer, and returns the number of bytes written and an error if any.

type ItemChar

type ItemChar struct {
	// contains filtered or unexported fields
}

ItemChar captcha item of unicode characters

func NewItemChar

func NewItemChar(w int, h int, bgColor color.RGBA) *ItemChar

NewItemChar creates a captcha item of characters

func (*ItemChar) BinaryEncoding

func (item *ItemChar) BinaryEncoding() []byte

BinaryEncoding encodes an image to PNG and returns a byte slice.

func (*ItemChar) EncodeB64string

func (item *ItemChar) EncodeB64string() string

EncodeB64string encodes an image to base64 string

func (*ItemChar) WriteTo

func (item *ItemChar) WriteTo(w io.Writer) (int64, error)

WriteTo writes captcha character in png format into the given io.Writer, and returns the number of bytes written and an error if any.

type ItemDigit

type ItemDigit struct {
	*image.Paletted
	// contains filtered or unexported fields
}

ItemDigit digits captcha Struct

func NewItemDigit

func NewItemDigit(width int, height int, dotCount int, maxSkew float64) *ItemDigit

NewItemDigit create a instance of item-digit

func (*ItemDigit) EncodeB64string

func (m *ItemDigit) EncodeB64string() string

EncodeB64string encodes an image to base64 string

func (*ItemDigit) EncodeBinary

func (m *ItemDigit) EncodeBinary() []byte

EncodeBinary encodes an image to PNG and returns a byte slice.

func (*ItemDigit) WriteTo

func (m *ItemDigit) WriteTo(w io.Writer) (int64, error)

WriteTo writes captcha character in png format into the given io.Writer, and returns the number of bytes written and an error if any.

type RedisConfig

type RedisConfig struct {
	// Addr Redis地址,单机模式使用,如 "localhost:6379"
	Addr string
	// Addrs Redis集群地址列表,集群模式使用
	Addrs []string
	// Password Redis密码
	Password string
	// DB Redis数据库索引(0-15),集群模式不支持
	DB int
	// PoolSize 连接池大小
	PoolSize int
	// KeyPrefix Redis键前缀,默认为 "captcha:"
	KeyPrefix string
	// Expiration 验证码过期时间,默认10分钟
	Expiration time.Duration
	// MasterName 哨兵模式的主节点名称
	MasterName string
}

RedisConfig Redis配置

type Store

type Store interface {
	// Set 为验证码ID设置答案值
	Set(id string, value string) error

	// Get 返回验证码ID对应的存储值
	// clear 参数指示是否需要从存储中删除该验证码
	Get(id string, clear bool) string

	// Verify 直接验证验证码答案
	Verify(id, answer string, clear bool) bool
}

Store 存储接口 实现 Store 接口的对象可以用于处理验证码ID和答案的存储与检索, 替换默认的内存存储。

对象有责任在必要时删除过期和已使用的验证码 (例如,默认内存存储在存储一定数量的验证码后会在 Set 方法中收集它们)

func NewMemoryStore

func NewMemoryStore(collectNum int, expiration time.Duration) Store

NewMemoryStore 创建新的标准内存存储 collectNum: 触发垃圾回收的条目数阈值 expiration: 验证码过期时间 返回的存储需要通过 SetCustomStore 注册以替换默认存储

type StoreRedis

type StoreRedis struct {
	// contains filtered or unexported fields
}

StoreRedis Redis存储后端 使用Redis作为验证码的存储介质,支持分布式部署

func NewStoreRedis

func NewStoreRedis(config RedisConfig) *StoreRedis

NewStoreRedis 创建Redis存储实例 config: Redis配置

func NewStoreRedisWithClient

func NewStoreRedisWithClient(client redis.UniversalClient, expiration time.Duration, keyPrefix string) *StoreRedis

NewStoreRedisWithClient 使用现有Redis客户端创建存储实例 适用于已有Redis连接的场景

func (*StoreRedis) Close

func (s *StoreRedis) Close() error

Close 关闭Redis连接

func (*StoreRedis) Get

func (s *StoreRedis) Get(id string, clear bool) string

Get 获取验证码答案 id: 验证码ID clear: 是否在获取后删除

func (*StoreRedis) GetClient

func (s *StoreRedis) GetClient() redis.UniversalClient

GetClient 获取Redis客户端 可用于执行其他Redis操作

func (*StoreRedis) Ping

func (s *StoreRedis) Ping() error

Ping 检查Redis连接是否正常

func (*StoreRedis) Set

func (s *StoreRedis) Set(id string, value string) error

Set 存储验证码ID和答案 id: 验证码ID value: 验证码答案

func (*StoreRedis) SetContext

func (s *StoreRedis) SetContext(ctx context.Context)

SetContext 设置上下文

func (*StoreRedis) Verify

func (s *StoreRedis) Verify(id, answer string, clear bool) bool

Verify 验证验证码答案 id: 验证码ID answer: 用户输入的答案 clear: 验证后是否清除

type StoreSyncMap

type StoreSyncMap struct {
	// contains filtered or unexported fields
}

StoreSyncMap 使用 sync.Map 作为存储后端

func NewStoreSyncMap

func NewStoreSyncMap(liveTime time.Duration) *StoreSyncMap

NewStoreSyncMap 创建 StoreSyncMap 实例 liveTime: 验证码存活时间

func (StoreSyncMap) Get

func (s StoreSyncMap) Get(id string, clear bool) string

Get 获取验证码答案 id: 验证码ID clear: 是否在获取后删除

func (StoreSyncMap) Set

func (s StoreSyncMap) Set(id string, value string) error

Set 存储验证码ID和答案

func (StoreSyncMap) Verify

func (s StoreSyncMap) Verify(id, answer string, clear bool) bool

Verify 验证验证码答案

Directories

Path Synopsis
example of HTTP server that uses the captcha package.
example of HTTP server that uses the captcha package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL