package middleware import ( "net/http" "go.opentelemetry.io/otel/trace" ) type TracingMiddleware struct { } func NewTracingMiddleware() *TracingMiddleware { return &TracingMiddleware{} } func (m *TracingMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { traceId := r.Header.Get("X-Trace-Id") spanId := r.Header.Get("X-Span-Id") if traceId != "" && spanId != "" { TraceID, _ := trace.TraceIDFromHex(traceId) SpanID, _ := trace.SpanIDFromHex(spanId) ctx := r.Context() sc := trace.NewSpanContext(trace.SpanContextConfig{ TraceID: TraceID, SpanID: SpanID, Remote: true, }) ctx = trace.ContextWithRemoteSpanContext(ctx, sc) //next.ServeHTTP(w, r.WithContext(ctx)) } // 处理请求 next(w, r) } }