/
cloudservices
/
auth-service
Обзор
Документация
Войти
/
cloudservices
/
auth-service
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
master
pkg/xhttp/logging.go
68 строк
1 KB
Ivan Shibkikh
fix logging error status
27 июл 2026, 22:00
27 июл 2026, 22:00
df5a909
Код
Авторство
О чём код?
package xhttp import ( "log/slog" "net/http" "time" ) func Logging(logger *slog.Logger) Middleware { return func(next Handler) Handler { return func(w http.ResponseWriter, r *http.Request) error { start := time.Now() rw := &responseWriter{ ResponseWriter: w, } err := next(rw, r) duration := time.Since(start) requestID := GetRequestID(r) if err != nil { logger.Error("http error", "request_id", requestID, "error", err) if rw.status == 0 { // no response sent http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } } status := rw.status if status == 0 { status = http.StatusOK } logger.Info("http request", "request_id", requestID, "status", status, "method", r.Method, "path", r.URL.Path, "duration_ms", duration.Milliseconds(), ) return nil } } } type responseWriter struct { http.ResponseWriter status int bytes int } func (w *responseWriter) WriteHeader(status int) { w.status = status w.ResponseWriter.WriteHeader(status) } func (w *responseWriter) Write(b []byte) (int, error) { if w.status == 0 { w.status = http.StatusOK } n, err := w.ResponseWriter.Write(b) w.bytes += n return n, err }