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

Do not change response code after 204 #5

Merged
merged 1 commit into from
Sep 18, 2021

Conversation

hrist0stoichev
Copy link

There's a bug in the writerwrapper. If you call WriteHeader with either 204 or 304, shouldCompress would be set to false and then all subsequent calls to Write will result in directly calling the OriginWriter.Write but since the status code is not written to OriginWriter, it will set it to 200. Another side effect of this is that Write will not only set the status code to 200 but it will also write the content of data to Body which would not normally happen if the gzip middleware is not used. Instead, if you set the status code to 204 or 304, any calls to Write will fail with an error. The correct unit test for this would be:

func Test_writeWrapper_does_not_change_status_code_after_204(t *testing.T) {
	wrapper, recorder := newWrapper()

	wrapper.WriteHeader(http.StatusNoContent)
	n, err := wrapper.Write([]byte("something"))

	assert.Equal(t, 0, n)
	assert.Error(t, err)
	assert.Equal(t, http.StatusNoContent, recorder.Code)
	assert.Equal(t, []byte{}, recorder.Body.Bytes())
}

The problem is that recorder actually behaves differently from server.response and won't check for 204, 304 (the actual call that server.response makes is bodyAllowedForStatus(w.status)) so recorder will both manage to record the 204 status code and the body (which won't happen in reality). Yet, I didn't find a way to instantiate the actual server.response and test against it. So, in the unit tests, the body will be written but in actual use cases, an error will be thrown as expected.

Copy link
Owner

@nanmu42 nanmu42 left a comment

Choose a reason for hiding this comment

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

Yes, that makes more sense. It would make this middleware more resiliant under unexpected user code.

Thank you for your contribution and feedback!

@nanmu42 nanmu42 merged commit ac2e31b into nanmu42:v1 Sep 18, 2021
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.

3 participants