如何在 Go 中释放 http.Client? [英] How to release http.Client in Go?

查看:40
本文介绍了如何在 Go 中释放 http.Client?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为HTTP2连接构建了一个http.Client,我需要做些什么来释放客户端和使用的资源?

I built a http.Client for HTTP2 connection, what do I need to do to release the client and resource used?

推荐答案

http.客户端 不需要任何特殊的方式来释放使用过的".资源.当它变得无法访问时,它使用的内存将被垃圾收集器回收.

http.Client does not require any special way to free "used" resources. When it becomes unreachable, memory used by it will be reclaimed by the garbage collector.

http.Client 不存储连接或状态信息.文档甚至声明应该重用 http.Client:

http.Client does not store connection or state information. The documentation even states that http.Client should be reused:

客户端的传输通常具有内部状态(缓存的 TCP 连接),因此客户端应该被重用,而不是根据需要创建.多个 goroutine 并发使用客户端是安全的.

The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.

如果您使用(例如嵌入)http.Client 构建自己的客户端,并且分配必须显式释放的资源,请在其上提供您自己的 Close() 方法并记录使用您自己的实现的任何人都必须调用 Close() 如果不再需要它.

If you build your own client using (e.g. embedding) http.Client and you allocate resources that must be released explicitly, provide your own Close() method on it and document that anyone who uses your own implementation must call Close() if it is not needed anymore.

注意:

如果您使用 http.Client 来执行 HTTP 操作(如 Client.Do(), Client.Get(), Client.Post() 等),它们返回值 *http.Response,并且该响应确实包含连接、状态和其他资源,确实需要释放,通常通过 Response.Body.Close().引用 http 的包文档:

What you might confuse it with is that if you use an http.Client to do HTTP operations (like Client.Do(), Client.Get(), Client.Post() etc.), they return a value of *http.Response, and that response does hold a connection, state and other resources, which does need to be freed, typically via Response.Body.Close(). Quoting from the package doc of http:

客户端完成后必须关闭响应正文:

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

resp, err := http.Get("http://example.com/")
if err != nil {
  // handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...

它也记录在 Client.Get():

当 err 为 nil 时,resp 总是包含一个非 nil 的 resp.Body.调用者在完成读取后应关闭 resp.Body.

When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

这篇关于如何在 Go 中释放 http.Client?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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