add environment support of opentelemetry propagation for package gctx

This commit is contained in:
John Guo
2022-06-17 16:47:01 +08:00
parent 1597291ac3
commit 64c5222623

View File

@ -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")