golang简单易用的验证码生成插件库captcha的使用

Golang简单易用的验证码生成插件库captcha的使用

简介

Package captcha 提供了一个简单易用、不固执己见的验证码生成API。

为什么选择这个验证码生成器?

我想要一个简单且与框架无关的方式来生成验证码。它还应该足够灵活,至少允许我选择自己喜欢的字体。

安装

go get github.com/steambap/captcha

使用示例

下面是一个基本的使用示例,展示如何生成验证码并在HTTP处理程序中使用:

func handle(w http.ResponseWriter, r *http.Request) {
    // 创建一个150x50像素的验证码
    data, _ := captcha.New(150, 50)

    // session来自其他库,如gorilla/sessions
    session.Values["captcha"] = data.Text
    session.Save(r, w)
    // 将图像数据发送给客户端
    data.WriteImage(w)
}

示例图片

验证码示例

数学验证码示例

兼容性

这个包使用了Go 1.16中的embed包。如果由于某些原因你必须使用Go 1.16之前的版本,请在go.mod中引用这个模块的1.4版本之前的版本。

完整示例Demo

下面是一个完整的HTTP服务器示例,展示如何使用captcha生成和验证验证码:

package main

import (
	"fmt"
	"github.com/steambap/captcha"
	"net/http"
)

var captchaText string

func main() {
	http.HandleFunc("/captcha", generateCaptcha)
	http.HandleFunc("/verify", verifyCaptcha)
	
	fmt.Println("Server started at :8080")
	http.ListenAndServe(":8080", nil)
}

func generateCaptcha(w http.ResponseWriter, r *http.Request) {
	// 生成150x50像素的验证码
	data, err := captcha.New(150, 50)
	if err != nil {
		http.Error(w, "Failed to generate captcha", http.StatusInternalServerError)
		return
	}
	
	// 存储验证码文本用于验证
	captchaText = data.Text
	
	// 将验证码图片写入响应
	data.WriteImage(w)
}

func verifyCaptcha(w http.ResponseWriter, r *http.Request) {
	userInput := r.URL.Query().Get("input")
	
	if userInput == captchaText {
		fmt.Fprintf(w, "验证码正确!")
	} else {
		fmt.Fprintf(w, "验证码错误!")
	}
}

贡献

如果你发现了bug,欢迎贡献!详情请参考contributing.md

许可证

MIT


更多关于golang简单易用的验证码生成插件库captcha的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang简单易用的验证码生成插件库captcha的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang验证码生成库captcha使用指南

captcha是一个简单易用的Golang验证码生成库,它可以生成数字、字母或混合验证码图片。下面详细介绍其使用方法。

安装

go get github.com/dchest/captcha

基本使用

生成验证码

package main

import (
	"github.com/dchest/captcha"
	"net/http"
)

func main() {
	// 设置路由
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// 生成验证码ID
		id := captcha.New()
		
		// 将验证码ID写入cookie或session
		http.SetCookie(w, &http.Cookie{
			Name:  "captcha_id",
			Value: id,
		})
		
		// 生成验证码图片并写入响应
		captcha.WriteImage(w, id, captcha.StdWidth, captcha.StdHeight)
	})
	
	http.ListenAndServe(":8080", nil)
}

验证验证码

func verifyHandler(w http.ResponseWriter, r *http.Request) {
	// 从cookie获取验证码ID
	cookie, err := r.Cookie("captcha_id")
	if err != nil {
		http.Error(w, "验证码ID不存在", http.StatusBadRequest)
		return
	}
	
	// 获取用户输入的验证码
	userInput := r.FormValue("captcha")
	
	// 验证验证码
	if captcha.VerifyString(cookie.Value, userInput) {
		w.Write([]byte("验证码正确"))
	} else {
		w.Write([]byte("验证码错误"))
	}
}

高级配置

自定义验证码属性

func customCaptcha() {
	// 设置验证码长度
	captcha.SetCustomStore(captcha.NewMemoryStore(1000, 5)) // 5位验证码
	
	// 生成自定义验证码
	id := captcha.NewLen(6) // 6位验证码
	
	// 自定义图片大小
	captcha.WriteImage(w, id, 200, 80) // 宽200px, 高80px
}

使用自定义存储

默认使用内存存储,生产环境建议使用Redis等持久化存储:

type redisStore struct {
	client *redis.Client
}

func (s *redisStore) Set(id string, digits []byte) {
	s.client.Set(id, string(digits), time.Minute*5) // 5分钟过期
}

func (s *redisStore) Get(id string, clear bool) (digits []byte) {
	val, _ := s.client.Get(id).Result()
	if clear {
		s.client.Del(id)
	}
	return []byte(val)
}

func main() {
	// 初始化Redis客户端
	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	
	// 设置自定义存储
	captcha.SetCustomStore(&redisStore{client: rdb})
	
	// 其他代码...
}

生成base64编码的验证码

func base64Captcha() string {
	id := captcha.New()
	
	var buf bytes.Buffer
	if err := captcha.WriteImage(&buf, id, captcha.StdWidth, captcha.StdHeight); err != nil {
		return ""
	}
	
	return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes())
}

前端集成示例

<!DOCTYPE html>
<html>
<head>
	<title>验证码示例</title>
</head>
<body>
	<img id="captcha" src="/captcha" onclick="refreshCaptcha()">
	<input type="text" id="captchaInput" placeholder="请输入验证码">
	<button onclick="verifyCaptcha()">验证</button>
	
	<script>
		function refreshCaptcha() {
			document.getElementById('captcha').src = '/captcha?' + Date.now();
		}
		
		function verifyCaptcha() {
			const input = document.getElementById('captchaInput').value;
			fetch('/verify', {
				method: 'POST',
				body: JSON.stringify({captcha: input}),
				headers: {
					'Content-Type': 'application/json'
				}
			}).then(res => res.text())
			.then(text => alert(text));
		}
	</script>
</body>
</html>

注意事项

  1. 生产环境不要使用内存存储,建议使用Redis等持久化存储
  2. 验证码ID需要安全传输,建议使用HttpOnly的Cookie
  3. 可以定期清理过期的验证码数据
  4. 对于高安全性需求,可以增加验证码的复杂度或添加其他验证方式

captcha库简单易用,适合大多数Web应用的验证码需求。通过上述示例,你可以快速集成验证码功能到你的Golang应用中。

回到顶部