go runtime_error ai_generated true

HTTP:在已关闭的响应体上执行读取操作

http: read on closed response body

ID: go/http-response-body-not-closed

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2023-04-15首次发现

版本兼容性

版本状态引入弃用备注
Go 1.18 active
Go 1.19 active
Go 1.20 active
Go 1.21 active
Go 1.22 active

根因分析

在 http.Response.Body 已经被关闭后尝试从中读取数据,通常是由于过早关闭或多个协程共享该 body 导致。

English

Attempting to read from an http.Response.Body after it has already been closed, typically due to premature closing or multiple goroutines sharing the body.

generic

官方文档

https://pkg.go.dev/net/http#Response

解决方案

  1. 在检查错误后始终 defer resp.Body.Close(),并在 defer 作用域内读取 body
  2. 如果多个协程需要读取同一个 body,使用 sync.Once 或互斥锁

无效尝试

常见但无效的做法:

  1. 80% 失败

    Closing the body before reading makes the data unavailable; the body must be read first, then closed.

  2. 70% 失败

    If the body is already closed, ReadAll will panic; always check errors and ensure body is open.