hcaptcha

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 15 Imported by: 0

README

hcaptcha

hcaptcha 是一个图形验证码生成与验证库,支持自定义样式、干扰线、噪点等配置,具有较强的抗 AI 识别能力。

功能特性

  • 生成图形验证码
  • 支持自定义尺寸和字符长度
  • 支持自定义干扰配置(干扰线、噪点、旋转、变形)
  • 内置验证码存储和过期管理
  • 验证码使用后自动失效
  • 自动清理过期验证码

导入路径

import "gitee.com/hwfo/hwf/pkg/hcaptcha"

快速开始

生成验证码
package main

import (
    "fmt"
    "gitee.com/hwfo/hwf/pkg/hcaptcha"
)

func main() {
    // 生成验证码(宽度, 高度, 字符长度)
    captcha, err := hcaptcha.GenerateCaptcha(200, 80, 4)
    if err != nil {
        panic(err)
    }
    
    fmt.Println("验证码ID:", captcha.ID)
    fmt.Println("验证码值:", captcha.Value) // 仅调试用,生产环境不应返回给前端
    
    // 获取 Base64 图片(可直接用于 <img src="...">)
    imgBase64 := captcha.Base64Image()
    fmt.Println("图片:", imgBase64)
}
验证验证码
// 验证用户输入(大小写不敏感)
isValid := hcaptcha.VerifyCaptcha(captchaID, userInput)
if isValid {
    fmt.Println("验证成功")
} else {
    fmt.Println("验证失败")
}

API 参考

生成验证码
// 使用默认配置生成验证码
func GenerateCaptcha(width, height, length int) (*CaptchaData, error)

// 使用自定义配置生成验证码
func GenerateCaptchaWithConfig(width, height, length int, config *Config) (*CaptchaData, error)

参数说明:

  • width: 图片宽度(最小 100)
  • height: 图片高度(最小 40)
  • length: 验证码字符长度(1-8)
  • config: 自定义配置(可选)
验证验证码
func VerifyCaptcha(captchaID, value string) bool

验证成功返回 true,验证后验证码自动失效。

CaptchaData 结构
type CaptchaData struct {
    ID    string // 验证码ID
    Value string // 验证码值
    Image []byte // 验证码图片(PNG 格式)
}

// 获取 Base64 格式的图片(可直接用于 img 标签)
func (c *CaptchaData) Base64Image() string
Config 配置
type Config struct {
    LineCount       int     // 干扰线数量,默认 50
    NoiseDensity    float64 // 噪点密度,默认 0.01
    RotateRange     float64 // 旋转角度范围,默认 45 度
    DistortStrength float64 // 变形强度(0-1),默认 0.35
}

// 获取默认配置
func DefaultConfig() *Config

使用示例

在 HWF 框架中使用
// 生成验证码接口
func (m *AuthModule) GetCaptcha(c *hwf.ReqCtx) {
    captcha, err := hcaptcha.GenerateCaptcha(200, 80, 4)
    if err != nil {
        c.JSON(500, map[string]string{"error": err.Error()})
        return
    }
    
    c.JSON(200, map[string]string{
        "captcha_id": captcha.ID,
        "image":      captcha.Base64Image(),
    })
}

// 登录验证接口
func (m *AuthModule) Login(c *hwf.ReqCtx) {
    var req struct {
        Username  string `json:"username"`
        Password  string `json:"password"`
        CaptchaID string `json:"captcha_id"`
        Captcha   string `json:"captcha"`
    }
    if err := c.BindJSON(&req); err != nil {
        c.JSON(400, map[string]string{"error": err.Error()})
        return
    }
    
    // 验证验证码
    if !hcaptcha.VerifyCaptcha(req.CaptchaID, req.Captcha) {
        c.JSON(400, map[string]string{"error": "验证码错误"})
        return
    }
    
    // 验证用户名密码...
}
自定义配置
// 增强干扰效果
config := &hcaptcha.Config{
    LineCount:       80,    // 更多干扰线
    NoiseDensity:    0.02,  // 更多噪点
    RotateRange:     60,    // 更大旋转角度
    DistortStrength: 0.5,   // 更强变形
}

captcha, _ := hcaptcha.GenerateCaptchaWithConfig(200, 80, 4, config)

验证码有效期

  • 默认有效期:60 秒
  • 使用一次后自动失效
  • 可通过 hcaptcha.EffectiveDuration 修改有效期
import "time"

// 设置验证码有效期为 120 秒
hcaptcha.EffectiveDuration = 120 * time.Second

字符集

验证码使用以下字符集(排除了容易混淆的字符如 0、O、I 等):

12345678ABCDEFGHJKLMNPQRSTUVWXYZ

注意事项

  • 验证码验证不区分大小写
  • 每个验证码只能使用一次
  • 验证码 ID 应在表单中隐藏提交
  • 生产环境不要将 Value 返回给前端
  • 图片尺寸过小可能导致生成失败

Documentation

Index

Constants

This section is empty.

Variables

View Source
var EffectiveDuration = time.Second * 60 //

验证码有效期,默认60秒,使用一次后失效

Functions

func VerifyCaptcha

func VerifyCaptcha(captchaID, value string) bool

验证验证码

Types

type CaptchaData

type CaptchaData struct {
	ID    string // 验证码ID
	Value string // 验证码值
	Image []byte // 验证码图片base64编码
}

CaptchaData 验证码数据

func GenerateCaptcha

func GenerateCaptcha(width, height, length int) (*CaptchaData, error)

GenerateCaptcha 生成验证码

func GenerateCaptchaWithConfig

func GenerateCaptchaWithConfig(width, height, length int, config *Config) (*CaptchaData, error)

func (*CaptchaData) Base64Image

func (c *CaptchaData) Base64Image() string

type CaptchaImage

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

func NewCaptchaImage

func NewCaptchaImage(config *Config) *CaptchaImage

10个样本轻度测试效果 豆包识别率:10% ddddocr识别率:0%

func (*CaptchaImage) Generate

func (c *CaptchaImage) Generate(width, height, length int) ([]byte, string, error)

type Config

type Config struct {
	LineCount       int     // 干扰线数量
	NoiseDensity    float64 // 噪点密度
	RotateRange     float64 // 旋转角度范围
	DistortStrength float64 // 变形强度(0-1),0表示无变形,1表示最大变形
}

Config 验证码配置

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 默认配置

Jump to

Keyboard shortcuts

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