我正在发出不需要回复的请求.如果这样做,会引起任何问题吗?
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)推荐答案
从 Client.Do()
如果返回的错误为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.引用自 http.Response :
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 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.
如果不需要身体,可以这样丢弃:
If you don't need the body, you may discard it like this:
resp, err := client.Do(req) if err != nil { // handle error and return return } defer resp.Close() io.Copy(ioutil.Discard, resp.Body)如果有错误,请参阅相关问题:如果在调用http.Get(url)时发生错误,我们是否需要关闭响应对象?
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()吗?
发布评论