Skip to content
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

read http response body before closing it #73

Merged
merged 2 commits into from
Dec 2, 2024

Conversation

erka
Copy link
Contributor

@erka erka commented Nov 28, 2024

Per golang documentation, it isn't enough just to close the response body.
It's the best to read it before closing. Otherwise, there could be the resource leakage.

More information at https://pkg.go.dev/net/http#Client.Do

Per golang documentation, it isn't enough just to close the response body.
It's the best to read it before closing. Otherwise, there could be the resource leakage.

More information at https://pkg.go.dev/net/http#Client.Do
Copy link
Collaborator

@kevinmcconnell kevinmcconnell left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @erka, I agree it's better to read the response before closing here.

I don't think there was any resource leakage in the previous form, though. Closing the body should be sufficient. But reading the body before closing makes the underlying connection available for re-use via keep-alive. In the case of these healthcheck requests that probably won't make a huge difference, but still, it's better (and tidier!) to do so 👍

internal/server/health_check.go Outdated Show resolved Hide resolved
@kevinmcconnell kevinmcconnell merged commit 9f69461 into basecamp:main Dec 2, 2024
1 check passed
@erka erka deleted the read-body-before-close branch December 2, 2024 21:30
@erka
Copy link
Contributor Author

erka commented Dec 3, 2024

@kevinmcconnell it's much better. Thank you.

I have a question about the checker. Is there a specific reason you use a shutdown channel instead of context.WithCancel for the health checker? Using context.WithCancel would allow passing a cancellable context to NewRequestWithContext instead of context.Background, potentially yielding earlier results in some cases.

@kevinmcconnell
Copy link
Collaborator

@erka that's a good point! Using the context for cancellation also means we can simplify the logic a bit, since we'll always know from the error whether it was a cancel or a timeout. And we won't have to worry about prioritizing the cancel in the select, because once it's cancelled any further requests would also be cancelled.

I've switched to this approach in bc8525d. Thanks for the suggestion!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants