gohttprequesttraceopen-telemetrykrakend

Inject trace context into header of a incoming 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 incoming request and propagate to another backend API.

I have this 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 loads 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!!!