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

编程入门 行业动态 更新时间:2024-10-26 14:36:14
本文介绍了如果我不需要响应,是否需要resp.Body.Close()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在发出不需要回复的请求.如果这样做,会引起任何问题吗?

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()吗?

本文发布于:2023-10-24 13:24:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524070.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我不   resp   Close   Body

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!