package telemetry import ( "context" "github.com/go-chi/chi/v5" mw "github.com/go-chi/chi/v5/middleware" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" "log/slog" "net/http" "strconv" "time" ) func HTTP(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx, sp := Start(Extract(r.Context(), r.Header.Get("traceparent"), r.Header.Get("tracestate")), "HTTP", trace.SpanKindServer) start := time.Now() ww := mw.NewWrapResponseWriter(w, r.ProtoMajor) defer func() { route := chi.RouteContext(ctx).RoutePattern() if route == "" { route = "unmatched" } method := r.Method switch method { case "GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS": default: method = "OTHER" } status := ww.Status() if status == 0 { status = 200 } sp.SetName(method + " " + route) sp.SetAttributes(attribute.String("http.route", route), attribute.String("http.request.method", method), attribute.Int("http.response.status_code", status)) if status >= 500 { sp.SetStatus(codes.Error, "server_error") } a := []attribute.KeyValue{attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", strconv.Itoa(status/100)+"xx")} Count(ctx, "messenger.http.requests", 1, a...) Duration(ctx, "messenger.http.duration", time.Since(start), a[:2]...) slog.InfoContext(ctx, "http_request", "method", method, "route", route, "status", status, "request_id", w.Header().Get("X-Request-Id")) sp.End() }() next.ServeHTTP(ww, r.WithContext(ctx)) }) } // RegisterRoute publishes zero counters before any outcome, preserving the first spike. func RegisterRoute(method, route string) { for _, class := range []string{"1xx", "2xx", "3xx", "4xx", "5xx"} { Count(context.Background(), "messenger.http.requests", 0, attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", class)) } }