/
t3
/
s3-server
Обзор
Документация
Войти
/
t3
/
s3-server
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
master
internal/api/middleware.go
80 строк
2 KB
Ivan
end-to-end logging
25 июл 2026, 00:10
25 июл 2026, 00:10
2107e02
Код
Авторство
О чём код?
package api import ( "log/slog" "net/http" "time" "github.com/google/uuid" ) // isValidRequestID checks that the request ID is a non-empty alphanumeric + hyphen string up to 64 chars. func isValidRequestID(rid string) bool { if rid == "" || len(rid) > 64 { return false } for _, c := range rid { if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' { continue } return false } return true } // RequestIDMiddleware reads or generates a request/correlation ID. // Accepts client-supplied X-Request-ID (validated). Otherwise generates a UUIDv4. // Sets the response header and adds it to the request context. func RequestIDMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rid := r.Header.Get("X-Request-ID") if !isValidRequestID(rid) { rid = uuid.NewString() } w.Header().Set("X-Request-ID", rid) ctx := WithRequestID(r.Context(), rid) next.ServeHTTP(w, r.WithContext(ctx)) }) } // statusRecorder wraps http.ResponseWriter to capture the status code and byte count. type statusRecorder struct { http.ResponseWriter status int written int64 } func (r *statusRecorder) WriteHeader(code int) { r.status = code r.ResponseWriter.WriteHeader(code) } func (r *statusRecorder) Write(b []byte) (int, error) { if r.status == 0 { r.status = http.StatusOK } n, err := r.ResponseWriter.Write(b) r.written += int64(n) return n, err } // LoggingMiddleware logs every request with method, path, status, duration, bytes, and request_id. func LoggingMiddleware(logger *slog.Logger) 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() sr := &statusRecorder{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(sr, r) logger.Info("request", "method", r.Method, "path", r.URL.Path, "status", sr.status, "bytes", sr.written, "duration", time.Since(start).String(), "request_id", RequestIDFromContext(r.Context()), ) }) } }