go - 如何在 Go 中发布 http.Client?

标签 go garbage-collection

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

最佳答案

http.Client不需要任何特殊方式来释放“已用”资源。当它变得不可访问时,它使用的内存将被垃圾收集器回收。

http.Client 不存储连接或状态信息。文档甚至指出 http.Client 应该被重用:

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()

注意:

您可能会混淆的是,如果您使用 http.Client 执行 HTTP 操作(如 Client.Do()Client.Get()Client.Post() 等),它们会返回一个值的 *http.Response ,并且该响应确实包含连接、状态和其他资源,这些资源确实需要释放,通常通过 Response.Body.Close() 释放。引用自 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() 中记录:

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

关于go - 如何在 Go 中发布 http.Client?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36688633/

相关文章:

go - 如何从相对路径使用动态链接库

go - 连接3个或更多 slice 的最简洁方法

ssl - 启用 SSL 后,Revel 不会转发到端口 443

sql - 为什么它需要在我的列名周围加上引号?

c - 如何在C中实现引用计数?

javascript - JS - 垃圾收集关闭?

wpf - 为什么在控件上使用弱事件模式而不是在其他地方管理生命周期?

go - 我什么时候应该在 Go 中定义值(而不是指针)的方法?

javascript - kinetic.js 中的删除和销毁有什么区别

c# - 我们应该使用 "workstation"垃圾回收还是 "server"垃圾回收?