Skip to content

Conversation

iwarapter
Copy link

When wrapping the server handler with a logging middleware, e.g:

type detailedResponseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (dw *detailedResponseWriter) WriteHeader(code int) {
	dw.statusCode = code
	dw.ResponseWriter.WriteHeader(code)
}

func (dw *detailedResponseWriter) StatusCode() int {
	return dw.statusCode
}

func Logger(log *slog.Logger) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			dw := &detailedResponseWriter{ResponseWriter: w}
			next.ServeHTTP(dw, r)
			log.InfoContext(r.Context(), "request log",
				slog.String("method", r.Method),
				slog.String("request_uri", r.URL.Path),
				slog.Any("duration", time.Since(start)),
				slog.Int("status_code", dw.StatusCode()))
		})
	}
}

because most of the underlying handlers rely on the http.Server defaulting the status at the very end - it is not possible to correctly get the status for endpoints which return a status 200.

This change just ensures a consistently setting the http status from all handlers.

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

Successfully merging this pull request may close these issues.

1 participant