Skip to content

Commit

Permalink
Fix status code tracing, where status code could be -1 (#438)
Browse files Browse the repository at this point in the history
  • Loading branch information
wimspaargaren authored Nov 16, 2021
1 parent c316677 commit def4a46
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
10 changes: 5 additions & 5 deletions component/http/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ func (w *responseWriter) Header() http.Header {

// Write to the internal responseWriter and sets the status if not set already.
func (w *responseWriter) Write(d []byte) (int, error) {
if !w.statusHeaderWritten {
w.status = http.StatusOK
w.statusHeaderWritten = true
}

value, err := w.writer.Write(d)
if err != nil {
return value, err
Expand All @@ -82,11 +87,6 @@ func (w *responseWriter) Write(d []byte) (int, error) {
w.responsePayload.Write(d)
}

if !w.statusHeaderWritten {
w.status = http.StatusOK
w.statusHeaderWritten = true
}

return value, err
}

Expand Down
42 changes: 42 additions & 0 deletions component/http/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -688,3 +688,45 @@ func TestIsConnectionReset(t *testing.T) {
})
}
}

type failWriter struct {
}

func (fw *failWriter) Header() http.Header {
return http.Header{}
}

func (fw *failWriter) Write([]byte) (int, error) {
return 0, fmt.Errorf("foo")
}

func (fw *failWriter) WriteHeader(statusCode int) {

}

func TestSetResponseWriterStatusOnResponseFailWrite(t *testing.T) {
failWriter := &failWriter{}
failDynamicCompressionResponseWriter := &dynamicCompressionResponseWriter{failWriter, "", nil, 0, deflateLevel}

tests := []struct {
Name string
ResponseWriter *responseWriter
}{
{
Name: "Failing responseWriter with http.ResponseWriter",
ResponseWriter: newResponseWriter(failWriter, false),
},
{
Name: "Failing responseWriter with http.ResponseWriter",
ResponseWriter: newResponseWriter(failDynamicCompressionResponseWriter, false),
},
}

for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
_, err := test.ResponseWriter.Write([]byte(`"foo":"bar"`))
assert.Error(t, err)
assert.Equal(t, http.StatusOK, test.ResponseWriter.status)
})
}
}

0 comments on commit def4a46

Please sign in to comment.