From 6946ddd22a373fb33c1f78392242294af5bc4fc4 Mon Sep 17 00:00:00 2001 From: dmathieu <42@dmathieu.com> Date: Wed, 24 Jul 2024 09:30:15 +0200 Subject: [PATCH] acquire the lock only once when writing --- .../otelhttp/internal/request/resp_writer_wrapper.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go b/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go index 5ddc20954dd..ca5c5e8c778 100644 --- a/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go +++ b/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go @@ -41,11 +41,11 @@ func NewRespWriterWrapper(w http.ResponseWriter, onWrite func(int64)) *RespWrite // Write writes the bytes array into the [ResponseWriter], and tracks the // number of bytes written and last error. func (w *RespWriterWrapper) Write(p []byte) (int, error) { - w.WriteHeader(http.StatusOK) - w.mu.RLock() defer w.mu.RUnlock() + w.writeHeader(http.StatusOK) + n, err := w.ResponseWriter.Write(p) n1 := int64(n) w.OnWrite(n1) @@ -63,6 +63,14 @@ func (w *RespWriterWrapper) WriteHeader(statusCode int) { w.mu.Lock() defer w.mu.Unlock() + w.writeHeader(statusCode) +} + +// writeHeader persists the status code for span attribution, and propagates +// the call to the underlying ResponseWriter. +// It does not acquire a lock, and therefore assumes that is being handled by a +// parent method. +func (w *RespWriterWrapper) writeHeader(statusCode int) { if !w.wroteHeader { w.wroteHeader = true w.statusCode = statusCode