如果我没有收到回应,会发生什么事情。在golang体内? [英] What could happen if I don't close response.Body in golang?

查看:140
本文介绍了如果我没有收到回应,会发生什么事情。在golang体内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

resp.Body.Close()

在这种情况下会发生什么?会不会有内存泄漏?在获得响应对象后立即将推迟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
}

如果出现错误,可以 resp resp.Body 是否为零?

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

推荐答案


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

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

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


在获取响应对象后立即将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 文档:

From the http.Client documentation:


出错时,可以忽略任何响应。非零错误的非零响应仅在CheckRedirect失败时发生,即使返回的Response.Body已经关闭。

On error, any Response can be ignored. A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and even then the returned Response.Body is already closed.

这篇关于如果我没有收到回应,会发生什么事情。在golang体内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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