如果我没有及时回复,身体会发生什么? [英] What could happen if I don't close response.Body?

查看:58
本文介绍了如果我没有及时回复,身体会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在获取响应对象之后立即放下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,则响应将包含一个非零的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.

这篇关于如果我没有及时回复,身体会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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