Help us shape the future of Go! Take the 2026 Go Developer Survey

captcha

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 8 Imported by: 0

README

Captcha 验证码工具包

基于 github.com/mojocn/base64Captcha 的验证码生成和验证工具包,支持多种验证码类型和存储方式。

特性

  • 支持多种验证码类型:数字、字符串、数学、中文、音频
  • 支持多种存储方式:内存存储、Redis存储
  • 提供全局服务和实例服务两种使用方式
  • 完整的配置支持
  • 线程安全

安装

go get github.com/mojocn/base64Captcha
go get github.com/redis/go-redis/v9

快速开始

使用默认配置
package main

import (
    "fmt"
    "log"
    
    "github.com/wenpiner/last-admin-common/utils/captcha"
)

func main() {
    // 使用默认配置创建服务
    service, err := captcha.NewService(nil)
    if err != nil {
        log.Fatal(err)
    }
    defer service.Close()
    
    // 生成验证码
    result, err := service.Generate()
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("验证码ID: %s\n", result.ID)
    fmt.Printf("验证码答案: %s\n", result.Answer)
    fmt.Printf("Base64图片: %s\n", result.Base64Blob)
    
    // 验证验证码
    isValid := service.VerifyAndClear(result.ID, result.Answer)
    fmt.Printf("验证结果: %t\n", isValid)
}
使用全局服务
package main

import (
    "fmt"
    "log"
    
    "github.com/wenpiner/last-admin-common/utils/captcha"
)

func main() {
    // 初始化全局服务
    config := captcha.DefaultConfig()
    config.Store.Type = captcha.StoreTypeMemory
    
    err := captcha.InitGlobalService(config)
    if err != nil {
        log.Fatal(err)
    }
    defer captcha.CloseGlobalService()
    
    // 使用全局函数
    result, err := captcha.Generate()
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("验证码ID: %s\n", result.ID)
    
    // 验证验证码
    isValid := captcha.VerifyAndClear(result.ID, result.Answer)
    fmt.Printf("验证结果: %t\n", isValid)
}

配置说明

验证码类型
// 支持的验证码类型
const (
    TypeDigit   = "digit"   // 数字验证码
    TypeString  = "string"  // 字符串验证码
    TypeMath    = "math"    // 数学验证码
    TypeChinese = "chinese" // 中文验证码
    TypeAudio   = "audio"   // 音频验证码
    TypeRandom  = "random"  // 随机验证码类型
)
存储类型
// 支持的存储类型
const (
    StoreTypeMemory = "memory" // 内存存储
    StoreTypeRedis  = "redis"  // Redis存储
)
自定义配置
config := &captcha.CaptchaConfig{
    Type: captcha.TypeString,
    String: captcha.StringConfig{
        Height:     60,
        Width:      240,
        Length:     4,
        Source:     "abcdefghijklmnopqrstuvwxyz0123456789",
        NoiseCount: 0,
    },
    Store: captcha.StoreConfig{
        Type:      captcha.StoreTypeRedis,
        Expire:    5 * time.Minute,
        KeyPrefix: "captcha:",
        Redis: captcha.RedisConfig{
            Addr:     "localhost:6379",
            Password: "",
            DB:       0,
            PoolSize: 10,
        },
    },
}
随机验证码配置
config := &captcha.CaptchaConfig{
    Type: captcha.TypeRandom,
    Random: captcha.RandomConfig{
        EnabledTypes: []captcha.CaptchaType{
            captcha.TypeDigit,
            captcha.TypeString,
            captcha.TypeMath,
        },
        ExcludeAudio: true, // 排除音频验证码
    },
    Store: captcha.StoreConfig{
        Type:      captcha.StoreTypeMemory,
        Expire:    5 * time.Minute,
        KeyPrefix: "captcha:",
    },
}

API 参考

Service 方法
// 创建服务
func NewService(config *CaptchaConfig) (*Service, error)

// 生成不同类型的验证码
func (s *Service) Generate() (*CaptchaResult, error)
func (s *Service) GenerateDigit() (*CaptchaResult, error)
func (s *Service) GenerateString() (*CaptchaResult, error)
func (s *Service) GenerateMath() (*CaptchaResult, error)
func (s *Service) GenerateChinese() (*CaptchaResult, error)
func (s *Service) GenerateAudio() (*AudioCaptchaResult, error)
func (s *Service) GenerateRandom() (*CaptchaResult, error)

// 验证验证码
func (s *Service) Verify(id, answer string, clear bool) bool
func (s *Service) VerifyAndClear(id, answer string) bool

// 关闭服务
func (s *Service) Close() error
全局函数
// 初始化和管理全局服务
func InitGlobalService(config *CaptchaConfig) error
func GetGlobalService() *Service
func CloseGlobalService() error

// 全局生成函数
func Generate() (*CaptchaResult, error)
func GenerateDigit() (*CaptchaResult, error)
func GenerateString() (*CaptchaResult, error)
func GenerateMath() (*CaptchaResult, error)
func GenerateChinese() (*CaptchaResult, error)
func GenerateAudio() (*AudioCaptchaResult, error)
func GenerateRandom() (*CaptchaResult, error)

// 全局验证函数
func Verify(id, answer string, clear bool) bool
func VerifyAndClear(id, answer string) bool

使用示例

生成不同类型的验证码
service, _ := captcha.NewService(config)
defer service.Close()

// 数字验证码
digitResult, _ := service.GenerateDigit()

// 字符串验证码
stringResult, _ := service.GenerateString()

// 数学验证码
mathResult, _ := service.GenerateMath()

// 中文验证码
chineseResult, _ := service.GenerateChinese()

// 音频验证码
audioResult, _ := service.GenerateAudio()

// 随机验证码
randomResult, _ := service.GenerateRandom()
使用随机验证码
// 配置随机验证码
config := captcha.DefaultConfig()
config.Type = captcha.TypeRandom
config.Random.EnabledTypes = []captcha.CaptchaType{
    captcha.TypeDigit,
    captcha.TypeString,
    captcha.TypeMath,
}

service, err := captcha.NewService(config)
if err != nil {
    log.Fatal(err)
}
defer service.Close()

// 生成随机类型的验证码
result, err := service.GenerateRandom()
if err != nil {
    log.Fatal(err)
}

fmt.Printf("验证码ID: %s\n", result.ID)
fmt.Printf("验证码答案: %s\n", result.Answer)
使用Redis存储
config := captcha.DefaultConfig()
config.Store.Type = captcha.StoreTypeRedis
config.Store.Redis = captcha.RedisConfig{
    Addr:     "localhost:6379",
    Password: "your-password",
    DB:       0,
    PoolSize: 10,
}

service, err := captcha.NewService(config)
if err != nil {
    log.Fatal(err)
}
defer service.Close()

测试

运行测试:

go test -v ./utils/captcha

运行示例:

go test -v -run Example ./utils/captcha

注意事项

  1. Redis存储需要确保Redis服务器可用
  2. 音频验证码需要系统支持音频处理
  3. 中文验证码需要相应的字体文件
  4. 验证码有过期时间,默认5分钟
  5. 建议在生产环境中使用Redis存储以支持分布式部署

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CloseGlobalService

func CloseGlobalService() error

CloseGlobalService 关闭全局服务

func InitGlobalService

func InitGlobalService(config *CaptchaConfig) error

InitGlobalService 初始化全局验证码服务

Example

ExampleInitGlobalService 演示如何使用全局服务

// 创建配置
config := &CaptchaConfig{
	Type: TypeString,
	String: StringConfig{
		Height:     60,
		Width:      240,
		Length:     4,
		Source:     "abcdefghijklmnopqrstuvwxyz0123456789",
		NoiseCount: 0,
	},
	Store: StoreConfig{
		Type:      StoreTypeMemory,
		Expire:    5 * time.Minute,
		KeyPrefix: "captcha:",
	},
}

// 初始化全局服务
err := InitGlobalService(config)
if err != nil {
	log.Fatal(err)
}
defer CloseGlobalService()

// 使用全局函数生成验证码
result, err := Generate()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("验证码ID: %s\n", result.ID)
fmt.Printf("验证码答案: %s\n", result.Answer)

// 验证验证码
isValid := VerifyAndClear(result.ID, result.Answer)
fmt.Printf("验证结果: %t\n", isValid)

func Verify

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

Verify 使用全局服务验证验证码

func VerifyAndClear

func VerifyAndClear(id, answer string) bool

VerifyAndClear 使用全局服务验证验证码并清除

Types

type AudioCaptchaResult

type AudioCaptchaResult struct {
	ID         string `json:"id"`         // 验证码ID
	Base64Blob string `json:"base64Blob"` // Base64编码的音频数据
	Body       []byte `json:"body"`       // 原始音频数据
	Answer     string `json:"answer"`     // 验证码答案(仅用于测试)
}

AudioCaptchaResult 音频验证码生成结果

func GenerateAudio

func GenerateAudio() (*AudioCaptchaResult, error)

GenerateAudio 使用全局服务生成音频验证码

type AudioConfig

type AudioConfig struct {
	Length   int    `json:"length" yaml:"length"`     // 验证码长度
	Language string `json:"language" yaml:"language"` // 语言
}

AudioConfig 音频验证码配置

type CaptchaConfig

type CaptchaConfig struct {
	// 验证码类型配置
	Type CaptchaType `json:"type" yaml:"type"`

	// 数字验证码配置
	Digit DigitConfig `json:"digit" yaml:"digit"`

	// 字符串验证码配置
	String StringConfig `json:"string" yaml:"string"`

	// 数学验证码配置
	Math MathConfig `json:"math" yaml:"math"`

	// 中文验证码配置
	Chinese ChineseConfig `json:"chinese" yaml:"chinese"`

	// 音频验证码配置
	Audio AudioConfig `json:"audio" yaml:"audio"`

	// 存储配置
	Store StoreConfig `json:"store" yaml:"store"`

	// 随机验证码配置
	Random RandomConfig `json:"random" yaml:"random"`
}

CaptchaConfig 验证码配置

func DefaultConfig

func DefaultConfig() *CaptchaConfig

DefaultConfig 返回默认配置

type CaptchaResult

type CaptchaResult struct {
	ID          string `json:"id"`          // 验证码ID
	Base64Blob  string `json:"base64Blob"`  // Base64编码的图片数据
	Body        []byte `json:"body"`        // 原始图片数据
	Answer      string `json:"answer"`      // 验证码答案(仅用于测试)
	CaptchaType string `json:"captchaType"` // 验证码类型
}

CaptchaResult 验证码生成结果

func Generate

func Generate() (*CaptchaResult, error)

Generate 使用全局服务生成验证码

func GenerateChinese

func GenerateChinese() (*CaptchaResult, error)

GenerateChinese 使用全局服务生成中文验证码

func GenerateDigit

func GenerateDigit() (*CaptchaResult, error)

GenerateDigit 使用全局服务生成数字验证码

func GenerateMath

func GenerateMath() (*CaptchaResult, error)

GenerateMath 使用全局服务生成数学验证码

func GenerateRandom

func GenerateRandom() (*CaptchaResult, error)

GenerateRandom 使用全局服务生成随机类型验证码

func GenerateString

func GenerateString() (*CaptchaResult, error)

GenerateString 使用全局服务生成字符串验证码

type CaptchaType

type CaptchaType string

CaptchaType 验证码类型

const (
	TypeDigit   CaptchaType = "digit"   // 数字验证码
	TypeString  CaptchaType = "string"  // 字符串验证码
	TypeMath    CaptchaType = "math"    // 数学验证码
	TypeChinese CaptchaType = "chinese" // 中文验证码
	TypeAudio   CaptchaType = "audio"   // 音频验证码
	TypeRandom  CaptchaType = "random"  // 随机验证码类型
)

type ChineseConfig

type ChineseConfig struct {
	Height          int         `json:"height" yaml:"height"`                   // 图片高度
	Width           int         `json:"width" yaml:"width"`                     // 图片宽度
	NoiseCount      int         `json:"noiseCount" yaml:"noiseCount"`           // 干扰线数量
	ShowLineOptions int         `json:"showLineOptions" yaml:"showLineOptions"` // 显示线条选项
	Length          int         `json:"length" yaml:"length"`                   // 验证码长度
	Source          string      `json:"source" yaml:"source"`                   // 中文字符源
	BgColor         *color.RGBA `json:"bgColor" yaml:"bgColor"`                 // 背景色
	Fonts           []string    `json:"fonts" yaml:"fonts"`                     // 字体列表
}

ChineseConfig 中文验证码配置

type DigitConfig

type DigitConfig struct {
	Height   int     `json:"height" yaml:"height"`     // 图片高度
	Width    int     `json:"width" yaml:"width"`       // 图片宽度
	Length   int     `json:"length" yaml:"length"`     // 验证码长度
	MaxSkew  float64 `json:"maxSkew" yaml:"maxSkew"`   // 最大倾斜角度
	DotCount int     `json:"dotCount" yaml:"dotCount"` // 干扰点数量
}

DigitConfig 数字验证码配置

type MathConfig

type MathConfig struct {
	Height          int         `json:"height" yaml:"height"`                   // 图片高度
	Width           int         `json:"width" yaml:"width"`                     // 图片宽度
	NoiseCount      int         `json:"noiseCount" yaml:"noiseCount"`           // 干扰线数量
	ShowLineOptions int         `json:"showLineOptions" yaml:"showLineOptions"` // 显示线条选项
	BgColor         *color.RGBA `json:"bgColor" yaml:"bgColor"`                 // 背景色
	Fonts           []string    `json:"fonts" yaml:"fonts"`                     // 字体列表
}

MathConfig 数学验证码配置

type MemoryStore

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

MemoryStore 内存存储实现

func NewMemoryStore

func NewMemoryStore(collectNum int, expiration time.Duration) *MemoryStore

NewMemoryStore 创建内存存储

func (*MemoryStore) Clear

func (m *MemoryStore) Clear(id string)

Clear 清除验证码

func (*MemoryStore) Close

func (m *MemoryStore) Close() error

Close 关闭内存存储(空实现)

func (*MemoryStore) Get

func (m *MemoryStore) Get(id string, clear bool) string

Get 获取验证码

func (*MemoryStore) Set

func (m *MemoryStore) Set(id string, value string) error

Set 存储验证码

func (*MemoryStore) Verify

func (m *MemoryStore) Verify(id, answer string, clear bool) bool

Verify 验证验证码

type RandomConfig

type RandomConfig struct {
	EnabledTypes []CaptchaType `json:"enabledTypes" yaml:"enabledTypes"` // 启用的验证码类型
	ExcludeAudio bool          `json:"excludeAudio" yaml:"excludeAudio"` // 是否排除音频验证码
}

RandomConfig 随机验证码配置

type RedisConfig

type RedisConfig struct {
	Addr     string `json:"addr" yaml:"addr"`         // Redis地址
	Password string `json:"password" yaml:"password"` // Redis密码
	DB       int    `json:"db" yaml:"db"`             // Redis数据库
	PoolSize int    `json:"poolSize" yaml:"poolSize"` // 连接池大小
}

RedisConfig Redis配置

type RedisStore

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

RedisStore Redis存储实现

Example

ExampleRedisStore 演示如何使用Redis存储

// 注意:这个示例需要Redis服务器运行在localhost:6379
config := &CaptchaConfig{
	Type: TypeMath,
	Store: StoreConfig{
		Type:      StoreTypeRedis,
		Expire:    10 * time.Minute,
		KeyPrefix: "captcha:",
		Redis: RedisConfig{
			Addr:     "localhost:6379",
			Password: "",
			DB:       0,
			PoolSize: 10,
		},
	},
}

service, err := NewService(config)
if err != nil {
	log.Printf("Redis连接失败,跳过示例: %v", err)
	return
}
defer service.Close()

// 生成数学验证码
result, err := service.GenerateMath()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("验证码ID: %s\n", result.ID)
fmt.Printf("验证码答案: %s\n", result.Answer)

// 验证验证码
isValid := service.VerifyAndClear(result.ID, result.Answer)
fmt.Printf("验证结果: %t\n", isValid)

func NewRedisStore

func NewRedisStore(config RedisConfig, keyPrefix string, expire time.Duration) (*RedisStore, error)

NewRedisStore 创建Redis存储

func (*RedisStore) Clear

func (r *RedisStore) Clear(id string)

Clear 清除验证码

func (*RedisStore) Close

func (r *RedisStore) Close() error

Close 关闭Redis连接

func (*RedisStore) Get

func (r *RedisStore) Get(id string, clear bool) string

Get 获取验证码

func (*RedisStore) Set

func (r *RedisStore) Set(id string, value string) error

Set 存储验证码

func (*RedisStore) Verify

func (r *RedisStore) Verify(id, answer string, clear bool) bool

Verify 验证验证码

type Service

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

Service 验证码服务

func GetGlobalService

func GetGlobalService() *Service

GetGlobalService 获取全局验证码服务

func NewService

func NewService(config *CaptchaConfig) (*Service, error)

NewService 创建验证码服务

func (*Service) Clear

func (s *Service) Clear(id string)

Clear 清除验证码

func (*Service) Close

func (s *Service) Close() error

Close 关闭服务

func (*Service) Generate

func (s *Service) Generate() (*CaptchaResult, error)

Generate 根据配置类型生成验证码

func (*Service) GenerateAudio

func (s *Service) GenerateAudio() (*AudioCaptchaResult, error)

GenerateAudio 生成音频验证码

func (*Service) GenerateChinese

func (s *Service) GenerateChinese() (*CaptchaResult, error)

GenerateChinese 生成中文验证码

func (*Service) GenerateDigit

func (s *Service) GenerateDigit() (*CaptchaResult, error)

GenerateDigit 生成数字验证码

Example

ExampleService_GenerateDigit 演示如何生成数字验证码

// 创建配置
config := DefaultConfig()
config.Store.Type = StoreTypeMemory // 使用内存存储用于示例

// 创建服务
service, err := NewService(config)
if err != nil {
	log.Fatal(err)
}
defer service.Close()

// 生成数字验证码
result, err := service.GenerateDigit()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("验证码ID: %s\n", result.ID)
fmt.Printf("验证码答案: %s\n", result.Answer)
fmt.Printf("Base64图片数据长度: %d\n", len(result.Base64Blob))

// 验证验证码
isValid := service.VerifyAndClear(result.ID, result.Answer)
fmt.Printf("验证结果: %t\n", isValid)

func (*Service) GenerateMath

func (s *Service) GenerateMath() (*CaptchaResult, error)

GenerateMath 生成数学验证码

func (*Service) GenerateRandom

func (s *Service) GenerateRandom() (*CaptchaResult, error)

GenerateRandom 生成随机类型的验证码

func (*Service) GenerateString

func (s *Service) GenerateString() (*CaptchaResult, error)

GenerateString 生成字符串验证码

func (*Service) Verify

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

Verify 验证验证码

func (*Service) VerifyAndClear

func (s *Service) VerifyAndClear(id, answer string) bool

VerifyAndClear 验证验证码并清除

type Store

type Store interface {
	base64Captcha.Store
	// Close 关闭存储连接
	Close() error
}

Store 验证码存储接口

func NewStore

func NewStore(config StoreConfig) (Store, error)

NewStore 根据配置创建存储实例

type StoreConfig

type StoreConfig struct {
	Type      StoreType     `json:"type" yaml:"type"`           // 存储类型
	Expire    time.Duration `json:"expire" yaml:"expire"`       // 过期时间
	KeyPrefix string        `json:"keyPrefix" yaml:"keyPrefix"` // Key前缀
	Redis     RedisConfig   `json:"redis" yaml:"redis"`         // Redis配置
}

StoreConfig 存储配置

type StoreType

type StoreType string

StoreType 存储类型

const (
	StoreTypeMemory StoreType = "memory" // 内存存储
	StoreTypeRedis  StoreType = "redis"  // Redis存储
)

type StringConfig

type StringConfig struct {
	Height          int         `json:"height" yaml:"height"`                   // 图片高度
	Width           int         `json:"width" yaml:"width"`                     // 图片宽度
	NoiseCount      int         `json:"noiseCount" yaml:"noiseCount"`           // 干扰线数量
	ShowLineOptions int         `json:"showLineOptions" yaml:"showLineOptions"` // 显示线条选项
	Length          int         `json:"length" yaml:"length"`                   // 验证码长度
	Source          string      `json:"source" yaml:"source"`                   // 字符源
	BgColor         *color.RGBA `json:"bgColor" yaml:"bgColor"`                 // 背景色
	Fonts           []string    `json:"fonts" yaml:"fonts"`                     // 字体列表
}

StringConfig 字符串验证码配置

Jump to

Keyboard shortcuts

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