WriteHeader is not called on 200s
Zach-Johnson opened this issue Β· comments
π Bug Report
I've written a simple http middleware that logs request information, including the status code of the response. On 200 responses, the status code logged is 0. For non-200 responses, I see the correct status code being logged. It seems like WriteHeader
is not called on successful responses and I think it should be.
To Reproduce
type statusRec struct {
http.ResponseWriter
status int
}
func (r *statusRec) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
func NewMiddleware(
l *zap.SugaredLogger,
) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
wrapped := &statusRec{ResponseWriter: w}
next.ServeHTTP(wrapped, r)
l.Infow("request",
"method", r.Method,
"path", r.URL.Path,
"duration", time.Since(start),
"status", wrapped.status,
)
})
}
}
func (s *Server) GetReport(ctx context.Context, req *pb.GetReportRequest) (*pb.GetReportResponse, error) {
// return &pb.GetReportResponse{}, status.Error(codes.Unknown, "err") // This will properly log the status code
// This will not log anything for the status code
return &pb.GetReportResponse{
Echo: req,
}, nil
}
// Attach the middleware to your runtime.Mux
Expected behavior
I expect that the request log contains a 200 for the response code
Actual Behavior
I see a zero for the status code in the request log
Your Environment
Local machine, v2.16.0
of grpc gateway, macOS
Thanks for your issue. The Go HTTP handler will automatically set the header to 200 if not otherwise called. There is no need to do it explicitly.