gohttprequesttraceopen-telemetrykrakend

Inject Trace Context into header of a incomming Request in Go. (Custom Plugin for KrakenD)


I want to create a Custom Plugin in Go and load it into KrakenD(text). With this plugin, I want to generate a Trace span Context(Root) and inject into Header of each incomming request and propagate to another BckEnd Api.

i have this piece of code :

import (
    "context"
    "fmt"
    "net/http"

    // jaegerPropagator "go.opentelemetry.io/contrib/propagators/jaeger"
    "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/propagation"
    "go.opentelemetry.io/otel/sdk/trace"
    otelTrace "go.opentelemetry.io/otel/trace"
)



func newTraceProvider() (*trace.TracerProvider, error) {
    traceExporter, err := stdouttrace.New(
        stdouttrace.WithPrettyPrint())
    if err != nil {
        return nil, err
    }

    traceProvider := trace.NewTracerProvider(
        trace.WithBatcher(traceExporter),
    )
    return traceProvider, nil
}

// This method takes an "http.Handler" and returns another "http.Handler" that modifies the incoming request
func (req registrable) registerHandlers(ctx context.Context, extra map[string]interface{}, handler http.Handler) (http.Handler, error) {

    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
                 otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{},   propagation.Baggage{}))


        // Set up trace provider.
        tracerProvider, err := newTraceProvider()
        fmt.Println(err)

        tracer := tracerProvider.Tracer(nameTracer)

        // Start a new server span using the tracer and the incoming request context
        newCtx, span := tracer.Start(
            ctx,
            "Root-Server-Span",
            otelTrace.WithSpanKind(otelTrace.SpanKindServer),
        )
        defer span.End() // Ensure the span is ended

        carrier := propagation.HeaderCarrier(req.Header)
        otel.GetTextMapPropagator().Inject(newCtx, carrier)


        // Call the next handler in the chain with the new context
        handler.ServeHTTP(w, req.WithContext(newCtx))
    }), nil
}

The plugin load with Success, but it cannot be injected into headers.

Ιs there anyone who knows about the above and can help me?


Solution

  • I forgot to put the name of the plugin in krakend. the problem solved!!!