Go 构建一个简单的验证码识别接口服务
一、应用背景
在某些自动化项目中(如自动登录、信息采集等),验证码成为阻碍自动化脚本的常见机制。为了绕过这一步,我们需要将验证码图像通过程序自动识别。传统使用 Python 较多,但对于需要部署为独立微服务的系统,Go 更具优势。
本文介绍如何使用 Go 和 Tesseract 打造一个简洁实用的 HTTP API 验证码识别服务。
更多内容访问ttocr.com或联系1436423940
二、项目结构
captcha-ocr/
├── main.go
├── go.mod
├── sample/
│ └── test.png
三、环境准备
安装 Tesseract
Linux / macOS:
sudo apt install tesseract-ocr
或
brew install tesseract
Windows 请从 GitHub 下载 Tesseract 安装包并配置环境变量。
初始化 Go 项目
go mod init captcha-ocr
go get github.com/otiai10/gosseract/v2
四、服务端代码实现
main.go 内容如下:
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/otiai10/gosseract/v2"
)
func recognizeCaptcha(w http.ResponseWriter, r *http.Request) {
// 限制仅支持 POST 请求
if r.Method != http.MethodPost {
http.Error(w, "Only POST supported", http.StatusMethodNotAllowed)
return
}
// 读取上传的文件
file, _, err := r.FormFile("image")
if err != nil {
http.Error(w, "Failed to read image: "+err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// 保存临时文件
tmpPath := "temp.png"
out, err := os.Create(tmpPath)
if err != nil {
http.Error(w, "Failed to save image", http.StatusInternalServerError)
return
}
defer os.Remove(tmpPath)
defer out.Close()
_, err = out.ReadFrom(file)
if err != nil {
http.Error(w, "Failed to write image", http.StatusInternalServerError)
return
}
// 创建 OCR 客户端
client := gosseract.NewClient()
defer client.Close()
client.SetImage(tmpPath)
text, err := client.Text()
if err != nil {
http.Error(w, "OCR failed", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "识别结果: %s\n", text)
}
func main() {
http.HandleFunc("/ocr", recognizeCaptcha)
fmt.Println("服务已启动,监听端口 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
五、测试接口
你可以使用 Postman 或 curl 命令测试:
curl -X POST -F "image=@sample/test.png" http://localhost:8080/ocr
输出示例:
识别结果: 7g2D
浙公网安备 33010602011771号