Skip to content

Commit

Permalink
fix: Prevent multiple calls to WriteHeader on the same response writer
Browse files Browse the repository at this point in the history
  • Loading branch information
ivov committed Jan 19, 2025
1 parent 603eead commit 80df011
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions internal/api/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,14 +152,21 @@ type wrappedResponseWriter struct {
http.ResponseWriter
statusCode int
bytesWritten int
wroteHeader bool // prevent metrics middleware (using httpsnoop) from calling WriteHeader multiple times on the same response writer
}

func (rw *wrappedResponseWriter) WriteHeader(statusCode int) {
rw.ResponseWriter.WriteHeader(statusCode)
rw.statusCode = statusCode
if !rw.wroteHeader {
rw.statusCode = statusCode
rw.ResponseWriter.WriteHeader(statusCode)
rw.wroteHeader = true
}
}

func (rw *wrappedResponseWriter) Write(b []byte) (int, error) {
if !rw.wroteHeader {
rw.WriteHeader(http.StatusOK)
}
bytes, err := rw.ResponseWriter.Write(b)
rw.bytesWritten += bytes
return bytes, err
Expand Down

0 comments on commit 80df011

Please sign in to comment.