feat(server-go): AI 巡检闭环后端(inspection_records + /inspections 幂等接口)

This commit is contained in:
weijuesen
2026-08-12 16:24:55 +08:00
parent b89ad5e865
commit 210bd6cefb
10 changed files with 354 additions and 3 deletions
+90
View File
@@ -0,0 +1,90 @@
package service
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"strings"
"time"
)
// AIBBox 检测框
type AIBBox struct {
X float64 `json:"x"`
Y float64 `json:"y"`
W float64 `json:"w"`
H float64 `json:"h"`
}
// AIDetection 单条检测结果
type AIDetection struct {
BBox AIBBox `json:"bbox"`
ClassName string `json:"class"`
Confidence float64 `json:"confidence"`
}
// AIDetectResponse /detect 响应
type AIDetectResponse struct {
Model string `json:"model"`
Detections []AIDetection `json:"detections"`
}
// AIClient ai-service HTTP 客户端
type AIClient struct {
baseURL string
client *http.Client
}
// NewAIClient 创建 AI 客户端
func NewAIClient(baseURL string) *AIClient {
return &AIClient{
baseURL: strings.TrimSuffix(baseURL, "/"),
client: &http.Client{Timeout: 30 * time.Second},
}
}
// Detect 上传图片到 ai-service /detect,返回检测结果(无状态接口,天然幂等)
func (c *AIClient) Detect(ctx context.Context, imageBytes []byte, filename string) (*AIDetectResponse, error) {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
part, err := writer.CreateFormFile("file", filename)
if err != nil {
return nil, err
}
if _, err := part.Write(imageBytes); err != nil {
return nil, err
}
if err := writer.Close(); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/detect", &body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("ai-service /detect 返回 %d: %s", resp.StatusCode, string(data))
}
var out AIDetectResponse
if err := json.Unmarshal(data, &out); err != nil {
return nil, err
}
return &out, nil
}
@@ -0,0 +1,74 @@
package service
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestAIClientDetectParsesResult(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("method = %s, want POST", r.Method)
}
if r.URL.Path != "/detect" {
t.Errorf("path = %s, want /detect", r.URL.Path)
}
if err := r.ParseMultipartForm(10 << 20); err != nil {
t.Errorf("multipart 解析失败: %v", err)
}
if _, _, err := r.FormFile("file"); err != nil {
t.Errorf("缺少 file 字段: %v", err)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"model": "mock",
"detections": []map[string]any{
{"bbox": map[string]float64{"x": 1, "y": 2, "w": 3, "h": 4}, "class": "sick", "confidence": 0.93},
},
})
}))
defer srv.Close()
client := NewAIClient(srv.URL)
res, err := client.Detect(context.Background(), []byte("image-bytes"), "a.png")
if err != nil {
t.Fatalf("Detect 返回错误: %v", err)
}
if res.Model != "mock" {
t.Errorf("model = %s, want mock", res.Model)
}
if len(res.Detections) != 1 {
t.Fatalf("detections 数量 = %d, want 1", len(res.Detections))
}
d := res.Detections[0]
if d.ClassName != "sick" || d.Confidence != 0.93 || d.BBox.W != 3 {
t.Errorf("解析结果不正确: %+v", d)
}
}
func TestAIClientDetectServerError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "boom", http.StatusInternalServerError)
}))
defer srv.Close()
_, err := NewAIClient(srv.URL).Detect(context.Background(), []byte("x"), "a.png")
if err == nil {
t.Error("服务端 500 应返回错误")
}
}
func TestAIClientDetectInvalidJSON(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("{bad"))
}))
defer srv.Close()
_, err := NewAIClient(srv.URL).Detect(context.Background(), []byte("x"), "a.png")
if err == nil {
t.Error("非法 JSON 应返回错误")
}
}