go
runtime_error
ai_generated
true
http: read on closed response body
ID: go/http-response-body-not-closed
90%Fix Rate
87%Confidence
1Evidence
2023-04-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Go 1.18 | active | — | — | — |
| Go 1.19 | active | — | — | — |
| Go 1.20 | active | — | — | — |
| Go 1.21 | active | — | — | — |
| Go 1.22 | active | — | — | — |
Root Cause
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中文
在 http.Response.Body 已经被关闭后尝试从中读取数据,通常是由于过早关闭或多个协程共享该 body 导致。
Official Documentation
https://pkg.go.dev/net/http#ResponseWorkarounds
-
95% success Always defer resp.Body.Close() after checking for error, and read the body inside the defer scope
Always defer resp.Body.Close() after checking for error, and read the body inside the defer scope
-
85% success Use a sync.Once or mutex if multiple goroutines need to read the same body
Use a sync.Once or mutex if multiple goroutines need to read the same body
中文步骤
在检查错误后始终 defer resp.Body.Close(),并在 defer 作用域内读取 body
如果多个协程需要读取同一个 body,使用 sync.Once 或互斥锁
Dead Ends
Common approaches that don't work:
-
80% fail
Closing the body before reading makes the data unavailable; the body must be read first, then closed.
-
70% fail
If the body is already closed, ReadAll will panic; always check errors and ensure body is open.