Avoid overwriting the written status code

When the response has been written, the status code saved in `responseWriter`
should no longer be changed by subsequent calls to `WriteHeader()`.

This fixes for example the logging possibly showing the wrong status code, or
any other middleware function checking the status code.
This commit is contained in:
Julio Guerra 2021-02-03 23:35:39 +01:00
parent e899771392
commit 4ea7d51dea
No known key found for this signature in database
GPG Key ID: 7CA5C9C05541F1B6
2 changed files with 5 additions and 0 deletions

View File

@ -61,6 +61,7 @@ func (w *responseWriter) WriteHeader(code int) {
if code > 0 && w.status != code {
if w.Written() {
debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code)
return
}
w.status = code
}

View File

@ -73,6 +73,10 @@ func TestResponseWriterWriteHeadersNow(t *testing.T) {
writer.size = 10
w.WriteHeaderNow()
assert.Equal(t, 10, w.Size())
w.WriteHeader(http.StatusOK)
assert.Equal(t, http.StatusMultipleChoices, w.Status())
assert.Equal(t, http.StatusMultipleChoices, testWriter.Code)
}
func TestResponseWriterWrite(t *testing.T) {