From cb7ab257995ba3020c187d910196d4dedb057b84 Mon Sep 17 00:00:00 2001 From: qydysky Date: Fri, 10 Nov 2023 00:06:27 +0800 Subject: [PATCH] 1 --- ctx/Ctx.go | 25 +++++++++++++++++++++++++ ctx/Ctx_test.go | 14 ++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/ctx/Ctx.go b/ctx/Ctx.go index 67c04d0..af11410 100644 --- a/ctx/Ctx.go +++ b/ctx/Ctx.go @@ -104,6 +104,13 @@ func Done(ctx context.Context) bool { return false } +// errCtx := pctx.Value[error]{} +// +// cancelC = errCtx.LinkCtx(cancelC) +// +// pctx.PutVal(cancelC, &errCtx, fmt.Errorf("%vs未接收到有效数据", readTO)) +// +// err := errCtx.Get() type Value[T any] struct { data T } @@ -125,3 +132,21 @@ func PutVal[T any](ctx context.Context, key *Value[T], v T) { pt.Set(v) } } + +var ( + selfCancel = "selfCancel" + ErrNotCarryYet = errors.New("ErrNotCarryYet") +) + +func CarryCancel(ctx context.Context, cancelFunc context.CancelFunc) context.Context { + return context.WithValue(ctx, &selfCancel, cancelFunc) +} + +func CallCancel(ctx context.Context) error { + if pt, ok := ctx.Value(&selfCancel).(context.CancelFunc); ok { + pt() + } else { + return ErrNotCarryYet + } + return nil +} diff --git a/ctx/Ctx_test.go b/ctx/Ctx_test.go index dd3a24d..4c9a47a 100644 --- a/ctx/Ctx_test.go +++ b/ctx/Ctx_test.go @@ -66,3 +66,17 @@ func TestMain3(t *testing.T) { t.Fatal() } } + +func TestMain4(t *testing.T) { + ctx := CarryCancel(context.WithCancel(context.Background())) + time.AfterFunc(time.Millisecond*500, func() { + if CallCancel(ctx) != nil { + t.Fail() + } + }) + n := time.Now() + <-ctx.Done() + if time.Since(n) < time.Millisecond*500 { + t.Fail() + } +} -- 2.39.2