用 Go 构建验证码识别 HTTP API(Tesseract 实现)
本项目将搭建一个 Web 服务,支持上传验证码图片并返回识别结果。后端使用 Go 语言,OCR 引擎为 Tesseract,轻量、实用、易部署。
一、功能简介
支持 HTTP 接口接收图片上传
使用 Tesseract 进行验证码识别
识别结果以 JSON 返回
可部署为独立服务,供前端或测试系统调用
二、依赖安装
安装 Tesseract OCR
Ubuntu:
更多内容访问ttocr.com或联系1436423940
sudo apt install tesseract-ocr
macOS:
brew install tesseract
安装依赖 Go 包
go get github.com/otiai10/gosseract/v2
go get github.com/gin-gonic/gin
三、完整代码示例
创建 main.go:
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
"github.com/otiai10/gosseract/v2"
)
func main() {
router := gin.Default()
// 上传识别接口
router.POST("/recognize", func(c *gin.Context) {
file, err := c.FormFile("image")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "图片上传失败"})
return
}
// 保存上传的文件
tmpPath := filepath.Join(os.TempDir(), file.Filename)
if err := c.SaveUploadedFile(file, tmpPath); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存图片失败"})
return
}
// OCR 识别
client := gosseract.NewClient()
defer client.Close()
client.SetImage(tmpPath)
client.SetWhitelist("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
text, err := client.Text()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "识别失败"})
return
}
c.JSON(http.StatusOK, gin.H{"result": text})
})
// 启动服务
router.Run(":8080")
}
四、运行与测试
启动服务
go run main.go
服务启动后监听 http://localhost:8080
使用 curl 测试
curl -X POST -F "image=@captcha.png" http://localhost:8080/recognize
输出示例:
{"result":"5G9K"}
五、接口说明
接口地址:POST /recognize
参数:表单字段名为 image 的文件
返回值:
成功:{"result": "验证码文本"}
失败:{"error": "错误信息"}
六、部署建议
使用 supervisor、systemd 等部署为后台服务
使用 Docker 容器打包部署
可接入前端页面进行验证码识别演示
浙公网安备 33010602011771号