fix: defer response body closure only when necessary to prevent premature stream termination

This commit is contained in:
2026-05-13 15:21:50 +03:00
parent 0896410906
commit 48d1342112
+3 -1
View File
@@ -290,9 +290,9 @@ func handleStreaming(
logger.Warn("[ANTHROPIC] Stream error [IP: %s]: %v", c.IP(), err) logger.Warn("[ANTHROPIC] Stream error [IP: %s]: %v", c.IP(), err)
return c.Status(fiber.StatusBadGateway).SendString("upstream error") return c.Status(fiber.StatusBadGateway).SendString("upstream error")
} }
defer resp.Body.Close()
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body) body, _ := io.ReadAll(resp.Body)
logger.Warn("[ANTHROPIC] Stream upstream %d [IP: %s]: %s", resp.StatusCode, c.IP(), string(body)) logger.Warn("[ANTHROPIC] Stream upstream %d [IP: %s]: %s", resp.StatusCode, c.IP(), string(body))
return c.Status(resp.StatusCode).Send(body) return c.Status(resp.StatusCode).Send(body)
@@ -308,6 +308,8 @@ func handleStreaming(
c.Set("Connection", "keep-alive") c.Set("Connection", "keep-alive")
c.Response().SetBodyStreamWriter(func(w *bufio.Writer) { c.Response().SetBodyStreamWriter(func(w *bufio.Writer) {
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body) scanner := bufio.NewScanner(resp.Body)
const maxScanTokenSize = 4 * 1024 * 1024 // 4 MB — Claude Code tool calls produce large chunks const maxScanTokenSize = 4 * 1024 * 1024 // 4 MB — Claude Code tool calls produce large chunks