如何在Go中发布http.Client? [英] How to release http.Client in Go?
问题描述
我为HTTP2连接构建了一个 http.Client
,我需要做些什么来释放客户端和资源?
感谢。
http.Client
不需要任何特殊的方式来释放已使用的资源。当它变得无法访问时,它使用的内存将被垃圾收集器收回。
http.Client
不会存储连接或状态信息。该文档甚至指出应该重用 http.Client
:
$ b
客户端的传输通常具有内部状态(高速缓存的TCP连接),所以客户端应该被重用,而不是根据需要创建。如果您使用(例如嵌入)
来构建自己的客户端,则可以使用
http.client
并且你分配必须明确释放的资源,提供你自己的Close()
方法并记录任何使用你自己的人如果不再需要,实现必须调用Close()
。
您可能会混淆的是,如果您使用
http.Client
来执行HTTP操作(如< a href =https://golang.org/pkg/net/http/#Client.Do =noreferrer>Client.Do()
,Client.Get()
,Client.Post()
等),它们返回值为* http.Response
,并且该响应确实需要释放 的连接,状态和其他资源,通常通过Response.Body.Close()
。从http
包文档中引用:
$ b
客户端必须关闭响应主体当完成它:
resp,err:= http.Get(http://example.com/)
if err!= nil {
//处理错误
}
defer resp.Body.Close()
body,err:= ioutil.ReadAll(resp.Body )
// ...
它也是记录在
Client.Get()
:
当err为零时,resp always包含一个非零的resp.Body。来电者在完成阅读后应关闭resp.Body。
I built a
http.Client
for HTTP2 connection, what do I need to do to release the client and resource used?Thanks.
解决方案
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
does not store connection or state information. The documentation even states thathttp.Client
should be reused: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.
If you build your own client using (e.g. embedding)
http.Client
and you allocate resources that must be released explicitly, provide your ownClose()
method on it and document that anyone who uses your own implementation must callClose()
if it is not needed anymore.Note:
What you might confuse it with is that if you use an
http.Client
to do HTTP operations (likeClient.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 viaResponse.Body.Close()
. Quoting from the package doc ofhttp
: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) // ...
It is also documented at
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中发布http.Client?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!