about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAlan Pearce2024-05-17 11:00:52 +0200
committerAlan Pearce2024-05-17 12:21:19 +0200
commitc5c9f726cae4cf4488312338da9599da53ac8b6c (patch)
treee9ccf2fcfa2546c3616b206946aa7e868f31e2e8
parentb8da487f774aa2399b79bbde5f2e6e13be4fce1c (diff)
downloadsearchix-c5c9f726cae4cf4488312338da9599da53ac8b6c.tar.lz
searchix-c5c9f726cae4cf4488312338da9599da53ac8b6c.tar.zst
searchix-c5c9f726cae4cf4488312338da9599da53ac8b6c.zip
fix(logging): track whether headers are written properly
-rw-r--r--internal/server/logging.go23
1 files changed, 20 insertions, 3 deletions
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 {