即使我不读取HTTP请求的响应体,我是否需要关闭它?

huangapple go评论87阅读模式
英文:

Do I need to close Response body of http request even if I don't read it?

问题

我有以下代码:

resp, err := http.Head("http:something.com")
if err != nil {
	//做一些处理
}

if resp.StatusCode == http.StatusOK {
	//做一些处理
}

由于我没有读取resp的body,我假设我不需要像resp.Body.Close()那样关闭它。我的假设是正确的吗?还是我仍然应该调用resp.Body.Close()

英文:

I have the following code:

resp, err = http.Head("http:something.com")
if err != nil {
	//do something
}

if resp.StatusCode == http.StatusOK {
	// do something		
}

As I am not reading the body of the resp I am assuming that I don't need to close it like resp.Body.Close(). Am I right in my assumption or should I still call resp.Body.Close()?

答案1

得分: 6

http.Head() 是对 DefaultClient.Head() 的封装,它调用了 Client.Do(),文档中说明:

> 如果返回的错误为nil,Response将包含一个非nil的Body,用户应该关闭它。如果没有将Body读取到EOF并关闭,Client的底层RoundTripper(通常是Transport)可能无法在后续的“keep-alive”请求中重用与服务器的持久TCP连接。

这应该足够让你关闭它。

即使你使用的是HTTP HEAD方法,这只是对服务器的一种“建议”。一个不符合RFC的服务器可能会返回一个body,即使不应该返回(对于HEAD请求),而Go的net/http库可能会通过Response.Body提供该body。所以你应该关闭它。即使没有发送或呈现给你任何body,关闭它也不会造成任何损害。

英文:

http.Head() is a wrapper around DefaultClient.Head() which issues Client.Do() which documents that:

> 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.

This should be enough for you to close it.

Even though you're using HTTP HEAD method, this is just more of a "recommendation" to the server. A server that does not conform to RFC may return a body even if it shouldn't (for a HEAD request), and Go's net/http library may provide that body via Response.Body. So you should close it. Even if no body is sent or presented to you, closing it will do no harm.

huangapple
  • 本文由 发表于 2022年1月6日 15:27:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/70603781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定