gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:40:28 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What could happen if I don't close response.Body?

(5 个回答)


2年前关闭。




我正在提出不需要回应的请求。如果我这样做会导致任何问题吗?

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

最佳答案

引用 Client.Do() 的文档

If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. If the Body is not both read to EOF and closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request.



所以是的,如果没有错误,你总是必须关闭它。您还应该在关闭之前将正文阅读到 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.


如果你不需要 body ,你可以像这样丢弃它:
resp, err := client.Do(req)
if err != nil {
// handle error and return
return
}
defer resp.Close()
io.Copy(ioutil.Discard, resp.Body)

如果有错误,请参阅相关问题: Do we need to close the response object if an error occurs while calling http.Get(url)?

关于http - 如果我不需要响应,是否需要 resp.Body.Close()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60931535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com