Skip to content

Commit

Permalink
Fix superfluous writing header after flush in otelhttp (#6074)
Browse files Browse the repository at this point in the history
Closes #6073

---------

Co-authored-by: Damien Mathieu <[email protected]>
  • Loading branch information
amanakin and dmathieu authored Sep 5, 2024
1 parent 673a225 commit 4f6b6c3
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

### Fixed

- Superfluous call to `WriteHeader` when flushing after setting a status code in `go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp`. (#6074)
- 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 -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,12 @@ func (w *RespWriterWrapper) writeHeader(statusCode int) {

// Flush implements [http.Flusher].
func (w *RespWriterWrapper) Flush() {
w.WriteHeader(http.StatusOK)
w.mu.Lock()
defer w.mu.Unlock()

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

if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
Expand Down
23 changes: 23 additions & 0 deletions instrumentation/net/http/otelhttp/test/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,12 @@ func (rw *respWriteHeaderCounter) WriteHeader(statusCode int) {
rw.ResponseWriter.WriteHeader(statusCode)
}

func (rw *respWriteHeaderCounter) Flush() {
if f, ok := rw.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}

func TestHandlerPropagateWriteHeaderCalls(t *testing.T) {
testCases := []struct {
name string
Expand Down Expand Up @@ -265,6 +271,23 @@ func TestHandlerPropagateWriteHeaderCalls(t *testing.T) {
},
expectHeadersWritten: []int{http.StatusBadRequest},
},
{
name: "When writing the header indirectly through flush",
handler: func(w http.ResponseWriter, r *http.Request) {
f := w.(http.Flusher)
f.Flush()
},
expectHeadersWritten: []int{http.StatusOK},
},
{
name: "With a header already written when flushing",
handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
f := w.(http.Flusher)
f.Flush()
},
expectHeadersWritten: []int{http.StatusBadRequest},
},
}

for _, tc := range testCases {
Expand Down

0 comments on commit 4f6b6c3

Please sign in to comment.