go runtime_error ai_generated true

http: read on closed response body

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

Also available as: JSON · Markdown · 中文
90%Fix Rate
87%Confidence
1Evidence
2023-04-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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#Response

Workarounds

  1. 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
  2. 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

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 70% fail

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