WriteHeader should be called once

Signed-off-by: Evgeniy Kulikov <kim@nspcc.ru>
This commit is contained in:
Evgeniy Kulikov 2020-11-27 15:28:27 +03:00
parent 1cd636a24b
commit 697d318a6b
2 changed files with 19 additions and 14 deletions

View file

@ -41,11 +41,11 @@ type (
} }
responseWrapper struct { responseWrapper struct {
sync.Once
http.ResponseWriter http.ResponseWriter
statusCode int statusCode int
headWritten bool startTime time.Time
startTime time.Time
} }
) )
@ -202,12 +202,10 @@ func (st *HTTPStats) updateStats(api string, w http.ResponseWriter, r *http.Requ
// WriteHeader - writes http status code // WriteHeader - writes http status code
func (w *responseWrapper) WriteHeader(code int) { func (w *responseWrapper) WriteHeader(code int) {
if !w.headWritten { w.Do(func() {
w.statusCode = code w.statusCode = code
w.headWritten = true
w.ResponseWriter.WriteHeader(code) w.ResponseWriter.WriteHeader(code)
} })
} }
// Flush - Calls the underlying Flush. // Flush - Calls the underlying Flush.

View file

@ -3,6 +3,7 @@ package api
import ( import (
"context" "context"
"net/http" "net/http"
"sync"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/gorilla/mux" "github.com/gorilla/mux"
@ -81,7 +82,9 @@ type (
mimeType string mimeType string
logResponseWriter struct { logResponseWriter struct {
sync.Once
http.ResponseWriter http.ResponseWriter
statusCode int statusCode int
} }
) )
@ -100,8 +103,10 @@ const (
var _ = logErrorResponse var _ = logErrorResponse
func (lrw *logResponseWriter) WriteHeader(code int) { func (lrw *logResponseWriter) WriteHeader(code int) {
lrw.statusCode = code lrw.Do(func() {
lrw.ResponseWriter.WriteHeader(code) lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
})
} }
func setRequestID(h http.Handler) http.Handler { func setRequestID(h http.Handler) http.Handler {
@ -139,12 +144,14 @@ func logErrorResponse(l *zap.Logger) mux.MiddlewareFunc {
zap.Int("status", lw.statusCode), zap.Int("status", lw.statusCode),
zap.String("method", mux.CurrentRoute(r).GetName()), zap.String("method", mux.CurrentRoute(r).GetName()),
zap.String("description", http.StatusText(lw.statusCode))) zap.String("description", http.StatusText(lw.statusCode)))
} else {
l.Info("call method", return
zap.Int("status", lw.statusCode),
zap.String("method", mux.CurrentRoute(r).GetName()),
zap.String("description", http.StatusText(lw.statusCode)))
} }
l.Info("call method",
zap.Int("status", lw.statusCode),
zap.String("method", mux.CurrentRoute(r).GetName()),
zap.String("description", http.StatusText(lw.statusCode)))
}) })
} }
} }