在接收到响应后延迟关闭 body。

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

Defer body.close after receiving response

问题

在使用 Go 语言编写的代码中,确保及时关闭 HTTP 响应体是一个良好的实践。这样做可以释放与响应相关的资源,并避免潜在的内存泄漏问题。在你提供的代码中,使用了 defer resp.Body.Close() 来确保在函数执行完毕后关闭响应体。这样无论代码中是否发生错误,都会保证响应体被正确关闭。因此,根据最佳实践,确保每次都关闭响应体是有必要的。

英文:
......
resp, err := httplib.Get(url)
if err != nil {
    fmt.Println(err)
}
defer resp.Body.Close()
......

Is it necessary to close the response body every time?

答案1

得分: 26

http包的官方文档中引用:

> 客户端在使用完响应体后必须关闭它

英文:

Quoting from the official documentation of the http package:

> The client must close the response body when finished with it

答案2

得分: 10

与最高票答案相反:是的,无论你是否使用它,关闭resp.Body都是必要的。

这是一个很好的问题,文档在这里非常误导人。在官方Go论坛的这个帖子中,诊断和结论 - 我自己也有过这种经历 - 是:

> 我导致服务器上的文件泄漏,所以我确认,即使你不读取它,你也必须关闭body。

英文:

Contrary to the top-voted answer: yes, it is necessary to close resp.Body whether you consume it or not.

This is a good question, and the docs are very misleading here. In this thread of the official Go forums, the diagnosis and conclusion -- which I have experienced for myself -- is:

> I was leading to leaking open files on the server, so I confirm, you MUST close the body, even if you don't read it

答案3

得分: 6

如果我们不关闭响应体会发生什么?

这是一个资源泄漏。它可能保持打开状态,客户端连接将无法重用。

建议在检查错误后立即关闭。

client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
    return nil, err
}
defer resp.Body.Close()

根据http.Client文档:

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

即使发生错误,底层的Transport也会关闭非nil的请求Body。

RoundTripper是什么?

它是指定单个HTTP请求的机制的Transport。如果为nil,则使用DefaultTransport。

英文:

> What happens if we do not close the response body ?

It is a resource leak. It can remain open and client connection will not be
reused.

It is recommended to close immediately after checking the error.

client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
    return nil, err
}
defer resp.Body.Close()

From the http.Client documentation:

> 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.
>
> The request Body, if non-nil, will be closed by the underlying
> Transport, even on errors.

What is RoundTripper ?

It is a Transport specifies the mechanism by which individual
HTTP requests are made.If nil, DefaultTransport is used.

huangapple
  • 本文由 发表于 2014年5月29日 16:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/23928983.html
匿名

发表评论

匿名网友

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

确定