Skip to content

Commit

Permalink
Don't write headers on Write if they were already written (#6055)
Browse files Browse the repository at this point in the history
The change in #5916 introduced a regression, as we don't check whether
the header was written before writing it in `Write()`.
We need to only write if the header wasn't written yet.

Fixes #6053.

---------

Co-authored-by: Tyler Yahn <[email protected]>
  • Loading branch information
dmathieu and MrAlias authored Aug 29, 2024
1 parent b62a80e commit 54d6916
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

- Drop support for [Go 1.21]. (#6046, #6047)

### Fixed

- Superfluous call to `WriteHeader` when writing the response body after setting a status code in `go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp`. (#6055)

<!-- Released section -->
<!-- Don't change this section unless doing release -->

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ func (w *RespWriterWrapper) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()

w.writeHeader(http.StatusOK)
if !w.wroteHeader {
w.writeHeader(http.StatusOK)
}

n, err := w.ResponseWriter.Write(p)
n1 := int64(n)
Expand Down
15 changes: 15 additions & 0 deletions instrumentation/net/http/otelhttp/test/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,21 @@ func TestHandlerPropagateWriteHeaderCalls(t *testing.T) {
},
expectHeadersWritten: []int{http.StatusInternalServerError, http.StatusOK},
},
{
name: "When writing the header indirectly through body write",
handler: func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("hello"))
},
expectHeadersWritten: []int{http.StatusOK},
},
{
name: "With a header already written when writing the body",
handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("hello"))
},
expectHeadersWritten: []int{http.StatusBadRequest},
},
}

for _, tc := range testCases {
Expand Down

0 comments on commit 54d6916

Please sign in to comment.