Files
obsx/http.go
T
M.ShakhmatovandClaude Fable 5.2 8837e8d316
CI / test (push) Successful in 1m12s
Deprecate v1.0.0 HTTP and log helpers in favour of the toolkit API
LogHandler and HTTPTransport now delegate to NewTraceHandler and
NewHTTPTransport. HTTPMiddleware keeps its v1.0.0 metric names but
shares responseWriter and normalizeMethod with NewHTTPMiddleware.
The package example shows obsx.New.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 16:43:33 +03:00

88 lines
3.1 KiB
Go

package obsx
import (
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
"go.opentelemetry.io/otel/trace"
)
// HTTPMiddleware returns server middleware that traces every request
// (continuing the trace from incoming headers) and, when m is not nil, records
// the http_requests_total{method,route,status} counter and the
// http_request_duration_seconds{method,route} histogram.
//
// The route is the matched http.ServeMux pattern (Request.Pattern), so wrap
// the mux itself; unmatched requests are reported as route "unmatched".
//
// Deprecated: use NewHTTPMiddleware (or Observer.HTTPMiddleware), which adds
// access logs, in-flight and exemplar support and uses the fleet-wide
// http_server_* metric names. HTTPMiddleware keeps its v1.0.0 metric names.
func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler {
var requests *prometheus.CounterVec
var duration *prometheus.HistogramVec
if m != nil {
requests = m.Counter("http_requests_total", "Total HTTP requests served.", "method", "route", "status")
duration = m.Histogram("http_request_duration_seconds", "HTTP request duration in seconds.", nil, "method", "route")
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
method := normalizeMethod(r.Method)
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
ctx, span := otel.Tracer(tracerName).Start(ctx, method,
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(semconv.HTTPRequestMethodKey.String(method), semconv.URLPath(r.URL.Path)),
)
defer span.End()
rw := &responseWriter{ResponseWriter: w}
r = r.WithContext(ctx)
defer func() {
// A panic propagates to net/http, which answers 500 or drops the connection.
p := recover()
status := rw.status
switch {
case p != nil:
status = http.StatusInternalServerError
case status == 0:
status = http.StatusOK
}
route := r.Pattern // set by ServeMux on this request during ServeHTTP
if route == "" {
route = routeUnmatched
} else {
span.SetName(route)
span.SetAttributes(semconv.HTTPRoute(route))
}
span.SetAttributes(semconv.HTTPResponseStatusCode(status))
if status >= 500 {
span.SetStatus(codes.Error, http.StatusText(status))
}
if m != nil {
requests.WithLabelValues(method, route, strconv.Itoa(status)).Inc()
duration.WithLabelValues(method, route).Observe(time.Since(start).Seconds())
}
if p != nil {
panic(p)
}
}()
next.ServeHTTP(rw, r)
})
}
}
// HTTPTransport wraps base (nil means http.DefaultTransport) so that every
// outgoing request gets a client span and carries the trace context headers.
//
// Deprecated: use NewHTTPTransport, which HTTPTransport now calls without metrics.
func HTTPTransport(base http.RoundTripper) http.RoundTripper {
return NewHTTPTransport(base, HTTPClientConfig{})
}