如果我不关闭 response.Body 会发生什么? [英] What could happen if I don't close response.Body?

查看:53
本文介绍了如果我不关闭 response.Body 会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Go 中,我有一些 http 响应,有时我忘记调用:

In Go, I have some http responses and I sometimes forget to call:

resp.Body.Close()

在这种情况下会发生什么?会不会有内存泄漏?在获取响应对象后立即放入 defer resp.Body.Close() 是否安全?

What happens in this case? will there be a memory leak? Also is it safe to put in defer resp.Body.Close() immediately after getting the response object?

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

如果出现错误怎么办,respresp.Body 是否可以为零?

What if there is an error, could resp or resp.Body be nil?

推荐答案

在这种情况下会发生什么?会不会有内存泄漏?

What happens in this case? will there be a memory leak?

这是资源泄漏.连接不会被重复使用,并且可以保持打开状态,在这种情况下不会释放文件描述符.

It's a resource leak. The connection won't be re-used, and can remain open in which case the file descriptor won't be freed.

在获得响应对象后立即放入 defer resp.Body.Close() 是否安全?

Also is it safe to put in defer resp.Body.Close() immediately after getting the response object?

否,请按照文档中提供的示例进行操作,并在检查错误后立即关闭.

No, follow the example provided in the documentation and close it immediately after checking the error.

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

来自 http.Client 文档:

如果返回的错误为 nil,则 Response 将包含一个非 nil 的 Body,用户应该关闭它.如果 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.

这篇关于如果我不关闭 response.Body 会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆