New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
net/http: proper way to close idle connections in http.DefaultTransport #42826
Comments
Only connections that are idle are closed so it really doesn't matter what does it, a Client or a Transport. |
@fraenkel Hi! Thanks for your message. |
You can call it on the client's transport if you type assert it to a http.Transport or an interface that defines the CloseIdleConnections(). |
So a better approach would be to use a custom Transport in production code and don’t bother with the default one at all? |
Its a judgement call. If the default values suit you, you can leverage it. If you want more control and guarantee that you aren't sharing the Transport with other bits of code, creating your own is safer. |
Okay, I understand. Thanks for helping me to figure this out! |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
I have a simple program that uses the default http transport:
http.DefautlTransport
and initializes two differenthttp.Client
(with different timeout settings for example) on top of it:https://play.golang.org/p/-AQxYXiG0El
I know that http transport keeps opened tcp connections in the pool and I want to close them before my program finishes because I don't need them anymore and it's a good practice to clean up resources.
I can call
firstHTTPClient.CloseIdleConnections()
andsecondHTTPClient.CloseIdleConnections()
it will close the underlyinghttp.DefaultTransport
connections, but it feels a bit as a side effect behavior. It will call.CloseIdleConnections()
on the same transport twice, it's not a problem, but again, feels a bit unoptimized.I would better instead close the transport directly and only one. But the problem is that
http.DefaultTranport
is an interface typehttp.RoundTripper
, nothttp.Transport
and it doesn't have.CloseIdleConnections()
method. In order to call it you need to assert the type:This is that you basically do in the
http.Client.CloseIdleConnections()
implementation. But It's inconvenient for the user code to do the type assertion on the default http transport every time. Wouldn't it be better to create a separate function and expose it to the user:You could actually reuse that function in the
http.Client.CloseIdleConnections()
implementation.The text was updated successfully, but these errors were encountered: