add init ctx feature (#1995)

This commit is contained in:
John Guo
2022-07-12 19:27:42 +08:00
committed by GitHub
parent e3665cedaf
commit f1766bdbdc
2 changed files with 24 additions and 2 deletions

View File

@ -23,8 +23,8 @@ type (
)
var (
// processCtx is the context initialized from process environment.
processCtx context.Context
processCtx context.Context // processCtx is the context initialized from process environment.
initCtx context.Context // initCtx is the context for init function of packages.
)
func init() {
@ -40,6 +40,8 @@ func init() {
context.Background(),
propagation.MapCarrier(m),
)
// Initialize initialization context.
initCtx = New()
}
// New creates and returns a context which contains context id.
@ -64,3 +66,14 @@ func WithCtx(ctx context.Context) context.Context {
func CtxId(ctx context.Context) string {
return gtrace.GetTraceID(ctx)
}
// SetInitCtx sets custom initialization context.
// Note that this function cannot be called in multiple goroutines.
func SetInitCtx(ctx context.Context) {
initCtx = ctx
}
// GetInitCtx returns the initialization context.
func GetInitCtx() context.Context {
return initCtx
}

View File

@ -30,3 +30,12 @@ func Test_WithCtx(t *testing.T) {
t.Assert(ctx.Value("TEST"), 1)
})
}
func Test_SetInitCtx(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
ctx := context.WithValue(context.TODO(), "TEST", 1)
gctx.SetInitCtx(ctx)
t.AssertNE(gctx.GetInitCtx(), "")
t.Assert(gctx.GetInitCtx().Value("TEST"), 1)
})
}