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

Automatically close request/response bodies when they are decoded #85

Merged
merged 6 commits into from
Mar 23, 2018

Conversation

obeattie
Copy link
Contributor

Request.Decode() and Response.Decode() are convenience methods that we use extensively for unmarshalling HTTP bodies. These are not suitable as methods that can be called repeatedly to yield multiple values in a streaming fashion. These methods' implementations however, used json.Decoder internally, which is meant for streaming use.

The problem with this is that json.Decoder may not read the entire stream: quite reasonably it reads only as much as it needs in order to yield a value, and presumes the stream is infinite. The way this was used inside .Decode() meant that a response body may never get closed. That's because it's common for a response body to be terminated with new line (\n) character, which the Decoder may leave unread. This would mean that the doneReader wouldn't see the body as being fully-read and leave it open.

This switches the implementations of .Decode() to use json.Unmarshal, which is not streaming. Instead of reading only chunks of the body, these methods now call .BodyBytes(), which explicitly closes the underlying reader.

The convenience method Decode() uses a JSON decoder internally. This can leave the end of the body, which typically consists of a terminating newline character, unread. This is undesirable: Decode() is a one-shot operation, and is not suitable for calling repeatedly to read multiple values anyway. To mitigate leaving the underlying reader "hanging" in this situation, the body is now closed within these methods.
@obeattie obeattie merged commit 5c63e48 into master Mar 23, 2018
@obeattie obeattie deleted the reader-closer branch March 23, 2018 07:40
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.

None yet

2 participants