/
cloudservices
/
common
Обзор
Документация
Войти
/
cloudservices
/
common
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
master
middleware/logging.go
57 строк
1 KB
Ivan
move middlewares into separate folder
26 июл 2026, 16:16
26 июл 2026, 16:16
a4dae25
Код
Авторство
О чём код?
package middleware import ( "log/slog" "net/http" "time" ) 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 } func Logging(logger *slog.Logger) Middleware { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rw := &responseWriter{ ResponseWriter: w, } next.ServeHTTP(rw, r) duration := time.Since(start) status := rw.status if status == 0 { status = http.StatusOK } logger.Info("http request", "status", status, "method", r.Method, "path", r.URL.Path, "duration_ms", duration.Milliseconds(), "request_id", r.Context().Value(RequestIDKey).(string), ) }) } }