Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

WriteHeader is not called on 200s #4031

Closed
Zach-Johnson opened this issue Feb 23, 2024 · 1 comment
Closed

WriteHeader is not called on 200s #4031

Zach-Johnson opened this issue Feb 23, 2024 · 1 comment

Comments

@Zach-Johnson
Copy link

馃悰 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

@johanbrandhorst
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants