diff --git a/bunrouterotel/middleware.go b/bunrouterotel/middleware.go index f9c3e84..7e7c6a5 100644 --- a/bunrouterotel/middleware.go +++ b/bunrouterotel/middleware.go @@ -2,6 +2,7 @@ package bunrouterotel import ( "net/http" + "strings" "github.com/uptrace/bunrouter" "go.opentelemetry.io/otel" @@ -13,9 +14,11 @@ import ( const ( tracerName = "git.blauwelle.com/go/crate/bunrouterotel" - version = "0.2.0" + version = "0.4.0" ) +var tracer = otel.Tracer(tracerName, trace.WithInstrumentationVersion("semver:"+version)) + type config struct { propagators propagation.TextMapPropagator } @@ -36,6 +39,15 @@ func WithPropagators(propagators propagation.TextMapPropagator) Option { }) } +func getForwardedFor(r *http.Request) []string { + h := r.Header.Get("X-Forwarded-For") + a := strings.Split(h, ",") + for i, s := range a { + a[i] = strings.Trim(s, " \t") + } + return a +} + // Middleware create a span, which record the request, // HTTP status code is NOT recorded. func Middleware(serverName string, opts ...Option) bunrouter.MiddlewareFunc { @@ -46,7 +58,6 @@ func Middleware(serverName string, opts ...Option) bunrouter.MiddlewareFunc { if cfg.propagators == nil { cfg.propagators = otel.GetTextMapPropagator() } - tracer := otel.Tracer(tracerName, trace.WithInstrumentationVersion("semver:"+version)) return func(next bunrouter.HandlerFunc) bunrouter.HandlerFunc { return func(w http.ResponseWriter, req bunrouter.Request) error { ctx := cfg.propagators.Extract(req.Context(), propagation.HeaderCarrier(req.Header)) @@ -75,6 +86,10 @@ func Middleware(serverName string, opts ...Option) bunrouter.MiddlewareFunc { attrs = append(attrs, attribute.String("http.route.param."+param.Key, param.Value)) } span.SetAttributes(attrs...) + forwardedFor := getForwardedFor(req.Request) + if forwardedFor != nil { + span.SetAttributes(attribute.StringSlice("http.forward_route", forwardedFor)) + } defer span.End() return next(w, req) }