Skip to content

Commit

Permalink
Don't write headers on Write if they were already written (open-tel…
Browse files Browse the repository at this point in the history
…emetry#6055)

The change in open-telemetry#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 open-telemetry#6053.

---------

Co-authored-by: Tyler Yahn <[email protected]>
  • Loading branch information
2 people authored and johnduhart committed Sep 6, 2024
1 parent fc25f67 commit 85d875f
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 @@ -8,6 +8,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

## [Unreleased]

### 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 85d875f

Please sign in to comment.