Merge PR #42: fix(sse): 修复非标准 SSE 格式解析问题

This commit is contained in:
shaw
2025-12-26 21:31:34 +08:00
3 changed files with 64 additions and 30 deletions

View File

@@ -10,6 +10,7 @@ import (
"io"
"log"
"net/http"
"regexp"
"strconv"
"strings"
"time"
@@ -20,6 +21,10 @@ import (
"github.com/google/uuid"
)
// sseDataPrefix matches SSE data lines with optional whitespace after colon.
// Some upstream APIs return non-standard "data:" without space (should be "data: ").
var sseDataPrefix = regexp.MustCompile(`^data:\s*`)
const (
testClaudeAPIURL = "https://api.anthropic.com/v1/messages"
testOpenAIAPIURL = "https://api.openai.com/v1/responses"
@@ -411,11 +416,11 @@ func (s *AccountTestService) processClaudeStream(c *gin.Context, body io.Reader)
}
line = strings.TrimSpace(line)
if line == "" || !strings.HasPrefix(line, "data: ") {
if line == "" || !sseDataPrefix.MatchString(line) {
continue
}
jsonStr := strings.TrimPrefix(line, "data: ")
jsonStr := sseDataPrefix.ReplaceAllString(line, "")
if jsonStr == "[DONE]" {
s.sendEvent(c, TestEvent{Type: "test_complete", Success: true})
return nil
@@ -465,11 +470,11 @@ func (s *AccountTestService) processOpenAIStream(c *gin.Context, body io.Reader)
}
line = strings.TrimSpace(line)
if line == "" || !strings.HasPrefix(line, "data: ") {
if line == "" || !sseDataPrefix.MatchString(line) {
continue
}
jsonStr := strings.TrimPrefix(line, "data: ")
jsonStr := sseDataPrefix.ReplaceAllString(line, "")
if jsonStr == "[DONE]" {
s.sendEvent(c, TestEvent{Type: "test_complete", Success: true})
return nil