From 48d1342112204e8cdd4fbf3a1dce80d36ddfc64a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beyhan=20O=C4=9Fur?= Date: Wed, 13 May 2026 15:21:50 +0300 Subject: [PATCH] fix: defer response body closure only when necessary to prevent premature stream termination --- handlers/anthropic.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/handlers/anthropic.go b/handlers/anthropic.go index 2fc02a9..94b98fb 100644 --- a/handlers/anthropic.go +++ b/handlers/anthropic.go @@ -290,9 +290,9 @@ func handleStreaming( logger.Warn("[ANTHROPIC] Stream error [IP: %s]: %v", c.IP(), err) return c.Status(fiber.StatusBadGateway).SendString("upstream error") } - defer resp.Body.Close() if resp.StatusCode != 200 { + defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) logger.Warn("[ANTHROPIC] Stream upstream %d [IP: %s]: %s", resp.StatusCode, c.IP(), string(body)) return c.Status(resp.StatusCode).Send(body) @@ -308,6 +308,8 @@ func handleStreaming( c.Set("Connection", "keep-alive") c.Response().SetBodyStreamWriter(func(w *bufio.Writer) { + defer resp.Body.Close() + scanner := bufio.NewScanner(resp.Body) const maxScanTokenSize = 4 * 1024 * 1024 // 4 MB — Claude Code tool calls produce large chunks