forked from mtusi2026/mtusi2026lab6
62 lines
2.2 KiB
Go
62 lines
2.2 KiB
Go
package fiber
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/fiber/v2/middleware/adaptor"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
)
|
|
|
|
// httpMetrics owns a per-server registry with bounded labels and no user identifiers.
|
|
type httpMetrics struct {
|
|
registry *prometheus.Registry
|
|
requests *prometheus.CounterVec
|
|
duration *prometheus.HistogramVec
|
|
active prometheus.Gauge
|
|
}
|
|
|
|
// newHTTPMetrics creates independent collectors so multiple test servers do not share state.
|
|
func newHTTPMetrics() *httpMetrics {
|
|
metrics := &httpMetrics{
|
|
registry: prometheus.NewRegistry(),
|
|
requests: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "messenger_http_requests_total", Help: "Completed requests by route, method and status class."}, []string{"route", "method", "status_class"}),
|
|
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "messenger_http_duration_seconds", Help: "Completed request latency.", Buckets: prometheus.DefBuckets}, []string{"route", "method"}),
|
|
active: prometheus.NewGauge(prometheus.GaugeOpts{Name: "messenger_http_in_flight", Help: "Currently executing HTTP requests."}),
|
|
}
|
|
metrics.registry.MustRegister(metrics.requests, metrics.duration, metrics.active)
|
|
return metrics
|
|
}
|
|
|
|
// observe records bounded route patterns, methods and status classes after error handling.
|
|
func (m *httpMetrics) observe(ctx *fiber.Ctx, elapsed time.Duration) {
|
|
route := "unmatched"
|
|
if ctx.Route() != nil && ctx.Route().Path != "/" {
|
|
route = ctx.Route().Path
|
|
}
|
|
method := ctx.Method()
|
|
switch method {
|
|
case http.MethodGet, http.MethodPost, http.MethodDelete, http.MethodHead, http.MethodOptions:
|
|
default:
|
|
method = "other"
|
|
}
|
|
status := "5xx"
|
|
switch ctx.Response().StatusCode() / 100 {
|
|
case 2:
|
|
status = "2xx"
|
|
case 3:
|
|
status = "3xx"
|
|
case 4:
|
|
status = "4xx"
|
|
}
|
|
m.requests.WithLabelValues(route, method, status).Inc()
|
|
m.duration.WithLabelValues(route, method).Observe(elapsed.Seconds())
|
|
}
|
|
|
|
// handleMetrics exposes this process's Prometheus registry without external backend calls.
|
|
func (ctrl *Controller) handleMetrics(ctx *fiber.Ctx) error {
|
|
return adaptor.HTTPHandler(promhttp.HandlerFor(ctrl.metrics.registry, promhttp.HandlerOpts{}))(ctx)
|
|
}
|