From c5c9f726cae4cf4488312338da9599da53ac8b6c Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Fri, 17 May 2024 11:00:52 +0200 Subject: fix(logging): track whether headers are written properly --- internal/server/logging.go | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) (limited to 'internal') diff --git a/internal/server/logging.go b/internal/server/logging.go index 6a16f42..ac8468f 100644 --- a/internal/server/logging.go +++ b/internal/server/logging.go @@ -4,23 +4,40 @@ import ( "fmt" "io" "net/http" + + "github.com/pkg/errors" ) type LoggingResponseWriter struct { + wroteHeader bool http.ResponseWriter statusCode int } func (lrw *LoggingResponseWriter) WriteHeader(code int) { lrw.statusCode = code - // avoids warning: superfluous response.WriteHeader call - if lrw.statusCode != http.StatusOK { + if !lrw.wroteHeader { lrw.ResponseWriter.WriteHeader(code) + lrw.wroteHeader = true + } +} + +func (lrw *LoggingResponseWriter) Write(b []byte) (int, error) { + if !lrw.wroteHeader { + lrw.statusCode = http.StatusOK + lrw.wroteHeader = true } + + count, err := lrw.ResponseWriter.Write(b) + if err != nil { + return count, errors.Wrap(err, "failed to write response") + } + + return count, nil } func NewLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter { - return &LoggingResponseWriter{w, http.StatusOK} + return &LoggingResponseWriter{false, w, http.StatusOK} } type wrappedHandlerOptions struct { -- cgit 1.4.1