Skip to content

Commit

Permalink
Fix bug in writing headers twice when serving metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
mostafa committed Sep 24, 2023
1 parent cb97fbe commit ab1bab5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
9 changes: 8 additions & 1 deletion cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,14 @@ var runCmd = &cobra.Command{
span.RecordError(err)
sentry.CaptureException(err)
}
next.ServeHTTP(responseWriter, request)
// The WriteHeader method intentionally does nothing, to prevent a bug
// in the merging metrics that causes the headers to be written twice,
// which results in an error: "http: superfluous response.WriteHeader call".
next.ServeHTTP(
&metrics.HeaderBypassResponseWriter{
ResponseWriter: responseWriter,
},
request)
}
return http.HandlerFunc(handler)
}
Expand Down
19 changes: 19 additions & 0 deletions metrics/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package metrics

import "net/http"

// HeaderBypassResponseWriter implements the http.ResponseWriter interface
// and allows us to bypass the response header when writing to the response.
// This is useful for merging metrics from multiple sources.
type HeaderBypassResponseWriter struct {
http.ResponseWriter
}

// WriteHeader intentionally does nothing, but is required to
// implement the http.ResponseWriter.
func (w *HeaderBypassResponseWriter) WriteHeader(code int) {}

// Write writes the data to the response.
func (w *HeaderBypassResponseWriter) Write(data []byte) (int, error) {
return w.ResponseWriter.Write(data)
}

0 comments on commit ab1bab5

Please sign in to comment.