如果我不需要响应,是否需要 resp.Body.Close() ?

use*_*039 1 http go

我正在提出请求,但不需要回复。如果我这样做会产生任何问题吗?

client = &http.Client{
    Timeout: time.Duration(15 * time.Second),
}
...
...
_, err := client.Do(req)
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 8

引用自文档Client.Do()

如果返回的错误为 nil,则 Response 将包含一个非 nil Body,用户应关闭该Body 。如果正文未读取到 EOF 并关闭,则客户端的底层 RoundTripper(通常为 Transport)可能无法重新使用与服务器的持久 TCP 连接来进行后续的“保持活动”请求。

所以是的,如果没有错误,您总是必须关闭它。您还需要在关闭之前将正文读至 EOF。引用自http.Response

// The default HTTP client's Transport may not
// reuse HTTP/1.x "keep-alive" TCP connections if the Body is
// not read to completion and closed.
Run Code Online (Sandbox Code Playgroud)

如果你不需要主体,你可以像这样丢弃它:

resp, err := client.Do(req)
if err != nil {
    // handle error and return
    return
}
defer resp.Close()
io.Copy(ioutil.Discard, resp.Body)
Run Code Online (Sandbox Code Playgroud)

如果出现错误,请参阅相关问题:如果调用 http.Get(url) 时发生错误,我们是否需要关闭响应对象?