如果我不需要响应,是否需要resp.Body.Close()吗? [英] Is resp.Body.Close() required if I don't need response?
问题描述
我正在发出不需要回复的请求.如果这样做,会引起任何问题吗?
I'm making request which I don't need response from. Would it cause any problems if I do it like this?
client = &http.Client{
Timeout: time.Duration(15 * time.Second),
}
...
...
_, err := client.Do(req)
推荐答案
从
如果返回的错误为nil,则响应将包含一个非nil的正文,希望用户关闭.如果未同时将Body读取到EOF并关闭,则客户端的基础RoundTripper(通常是Transport)可能无法将与服务器的持久TCP连接重新用于后续的保持活动"请求.
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.引用自 So yes, you always have to close it if there is no error. You are also expected to read the body to EOF before closing. Quoting from
如果不需要身体,可以这样丢弃: If you don't need the body, you may discard it like this: If there is an error, see related question: Do we need to close the response object if an error occurs while calling http.Get(url)? 这篇关于如果我不需要响应,是否需要resp.Body.Close()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
http.Response
: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.
resp, err := client.Do(req)
if err != nil {
// handle error and return
return
}
defer resp.Close()
io.Copy(ioutil.Discard, resp.Body)