package middleware import ( "net/http" "strconv" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" ) var ( httpRequestsTotal = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests", }, []string{"method", "path", "status"}, ) httpRequestDuration = promauto.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "Duration of HTTP requests", Buckets: []float64{0.1, 0.5, 1, 2.5, 5, 10}, }, []string{"method", "path"}, ) httpResponseSize = promauto.NewSummaryVec( prometheus.SummaryOpts{ Name: "http_response_size_bytes", Help: "Size of HTTP responses", }, []string{"method", "path"}, ) ) // MetricsMiddleware собирает метрики для Prometheus func MetricsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rw := &responseWriter{w, http.StatusOK, 0} next.ServeHTTP(rw, r) duration := time.Since(start).Seconds() status := strconv.Itoa(rw.status) // Регистрируем метрики httpRequestsTotal.WithLabelValues( r.Method, r.URL.Path, status, ).Inc() httpRequestDuration.WithLabelValues( r.Method, r.URL.Path, ).Observe(duration) httpResponseSize.WithLabelValues( r.Method, r.URL.Path, ).Observe(float64(rw.size)) }) }