diff --git a/os/gctx/gctx.go b/os/gctx/gctx.go index a81138379..e04066ae9 100644 --- a/os/gctx/gctx.go +++ b/os/gctx/gctx.go @@ -9,8 +9,12 @@ package gctx import ( "context" + "os" + "strings" "github.com/gogf/gf/v2/net/gtrace" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/propagation" ) type ( @@ -18,13 +22,36 @@ type ( StrKey string // StrKey is a type for warps basic type string as context key. ) +var ( + // processCtx is the context initialized from process environment. + processCtx context.Context +) + +func init() { + // All environment key-value pairs. + m := make(map[string]string) + i := 0 + for _, s := range os.Environ() { + i = strings.IndexByte(s, '=') + m[s[0:i]] = s[i+1:] + } + // OpenTelemetry from environments. + processCtx = otel.GetTextMapPropagator().Extract( + context.Background(), + propagation.MapCarrier(m), + ) +} + // New creates and returns a context which contains context id. func New() context.Context { - return WithCtx(context.Background()) + return WithCtx(processCtx) } // WithCtx creates and returns a context containing context id upon given parent context `ctx`. func WithCtx(ctx context.Context) context.Context { + if CtxId(ctx) != "" { + return ctx + } if gtrace.IsUsingDefaultProvider() { var span *gtrace.Span ctx, span = gtrace.NewSpan(ctx, "gctx.WithCtx")