fix: resolve openai compat lint issues

This commit is contained in:
amagi 2026-03-07 16:12:23 +08:00
parent 2660734a94
commit 84a143361b
2 changed files with 65 additions and 66 deletions

View file

@ -188,14 +188,18 @@ func (p *Provider) Chat(
// Non-200: read a prefix to tell HTML error page apart from JSON error body. // Non-200: read a prefix to tell HTML error page apart from JSON error body.
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(io.LimitReader(resp.Body, 256)) body, readErr := io.ReadAll(io.LimitReader(resp.Body, 256))
if err != nil { if readErr != nil {
return nil, fmt.Errorf("failed to read response: %w", err) return nil, fmt.Errorf("failed to read response: %w", readErr)
} }
if looksLikeHTML(body, contentType) { if looksLikeHTML(body, contentType) {
return nil, wrapHTMLResponseError(resp.StatusCode, body, contentType, p.apiBase) return nil, wrapHTMLResponseError(resp.StatusCode, body, contentType, p.apiBase)
} }
return nil, fmt.Errorf("API request failed:\n Status: %d\n Body: %s", resp.StatusCode, responsePreview(body, 128)) return nil, fmt.Errorf(
"API request failed:\n Status: %d\n Body: %s",
resp.StatusCode,
responsePreview(body, 128),
)
} }
// Peek without consuming so the full stream reaches the JSON decoder. // Peek without consuming so the full stream reaches the JSON decoder.
@ -218,7 +222,13 @@ func (p *Provider) Chat(
func wrapHTMLResponseError(statusCode int, body []byte, contentType, apiBase string) error { func wrapHTMLResponseError(statusCode int, body []byte, contentType, apiBase string) error {
respPreview := responsePreview(body, 128) respPreview := responsePreview(body, 128)
return fmt.Errorf("API request failed: %s returned HTML instead of JSON (content-type: %s); check api_base or proxy configuration.\n Status: %d\n Body: %s", apiBase, contentType, statusCode, respPreview) return fmt.Errorf(
"API request failed: %s returned HTML instead of JSON (content-type: %s); check api_base or proxy configuration.\n Status: %d\n Body: %s",
apiBase,
contentType,
statusCode,
respPreview,
)
} }
func looksLikeHTML(body []byte, contentType string) bool { func looksLikeHTML(body []byte, contentType string) bool {

View file

@ -3,6 +3,7 @@ package openai_compat
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -235,69 +236,57 @@ func TestProviderChat_JSONHTTPErrorDoesNotReportHTML(t *testing.T) {
} }
} }
func TestProviderChat_HTMLSuccessResponseReturnsHelpfulError(t *testing.T) { func TestProviderChat_HTMLResponsesReturnHelpfulError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tests := []struct {
w.Header().Set("Content-Type", "text/html; charset=utf-8") name string
w.WriteHeader(http.StatusOK) contentType string
_, _ = w.Write([]byte("<!DOCTYPE html><html><body>gateway login</body></html>")) statusCode int
})) body string
defer server.Close() }{
{
name: "html success response",
contentType: "text/html; charset=utf-8",
statusCode: http.StatusOK,
body: "<!DOCTYPE html><html><body>gateway login</body></html>",
},
{
name: "html error response",
contentType: "text/html; charset=utf-8",
statusCode: http.StatusBadGateway,
body: "<!DOCTYPE html><html><body>bad gateway</body></html>",
},
{
name: "mislabeled html success response",
contentType: "application/json",
statusCode: http.StatusOK,
body: " \r\n\t<!DOCTYPE html><html><body>gateway login</body></html>",
},
}
p := NewProvider("key", server.URL, "") for _, tt := range tests {
_, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "gpt-4o", nil) t.Run(tt.name, func(t *testing.T) {
if err == nil { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("expected error, got nil") w.Header().Set("Content-Type", tt.contentType)
} w.WriteHeader(tt.statusCode)
if !strings.Contains(err.Error(), "returned HTML instead of JSON") { _, _ = w.Write([]byte(tt.body))
t.Fatalf("expected helpful HTML error, got %v", err) }))
} defer server.Close()
if !strings.Contains(err.Error(), "check api_base or proxy configuration") {
t.Fatalf("expected configuration hint, got %v", err)
}
}
func TestProviderChat_HTMLErrorResponseReturnsHelpfulError(t *testing.T) { p := NewProvider("key", server.URL, "")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "gpt-4o", nil)
w.Header().Set("Content-Type", "text/html; charset=utf-8") if err == nil {
w.WriteHeader(http.StatusBadGateway) t.Fatal("expected error, got nil")
_, _ = w.Write([]byte("<!DOCTYPE html><html><body>bad gateway</body></html>")) }
})) if !strings.Contains(err.Error(), fmt.Sprintf("Status: %d", tt.statusCode)) {
defer server.Close() t.Fatalf("expected status code in error, got %v", err)
}
p := NewProvider("key", server.URL, "") if !strings.Contains(err.Error(), "returned HTML instead of JSON") {
_, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "gpt-4o", nil) t.Fatalf("expected helpful HTML error, got %v", err)
if err == nil { }
t.Fatal("expected error, got nil") if !strings.Contains(err.Error(), "check api_base or proxy configuration") {
} t.Fatalf("expected configuration hint, got %v", err)
if !strings.Contains(err.Error(), "Status: 502") { }
t.Fatalf("expected status code in error, got %v", err) })
}
if !strings.Contains(err.Error(), "returned HTML instead of JSON") {
t.Fatalf("expected helpful HTML error, got %v", err)
}
if !strings.Contains(err.Error(), "check api_base or proxy configuration") {
t.Fatalf("expected configuration hint, got %v", err)
}
}
func TestProviderChat_MislabeledHTMLSuccessResponseReturnsHelpfulError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(" \r\n\t<!DOCTYPE html><html><body>gateway login</body></html>"))
}))
defer server.Close()
p := NewProvider("key", server.URL, "")
_, err := p.Chat(t.Context(), []Message{{Role: "user", Content: "hi"}}, nil, "gpt-4o", nil)
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "returned HTML instead of JSON") {
t.Fatalf("expected helpful HTML error, got %v", err)
}
if !strings.Contains(err.Error(), "check api_base or proxy configuration") {
t.Fatalf("expected configuration hint, got %v", err)
} }
} }