From 7e6f947bf53ab7720d3bf6ace42de163e2dcb28a Mon Sep 17 00:00:00 2001 From: Orkun Karaduman Date: Fri, 4 Mar 2022 20:15:26 +0300 Subject: [PATCH] implemented NewTerminateContext2, WithTerminate2 --- terminatecontext.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/terminatecontext.go b/terminatecontext.go index 41dbfd5..3bfd9cc 100644 --- a/terminatecontext.go +++ b/terminatecontext.go @@ -24,13 +24,25 @@ func (c *terminateContext) Terminate() { // The code should call Terminate method or cancel function to release resources associated with it. func NewTerminateContext(ctx context.Context, cancel context.CancelFunc) TerminateContext { result := new(terminateContext) - result.Context = ctx - result.CancelFunc = cancel + result.Context, result.CancelFunc = ctx, cancel return result } +// NewTerminateContext2 is similar with NewTerminateContext. +// But it cancels the context when it was done through parent, deadline, timeout or in any way. +func NewTerminateContext2(ctx context.Context, cancel context.CancelFunc) TerminateContext { + AutoCancel(ctx, cancel) + return NewTerminateContext(ctx, cancel) +} + // WithTerminate creates a new cancel context as TerminateContext. // The code should call Terminate method to release resources associated with it, as cancel function. func WithTerminate(parent context.Context) TerminateContext { return NewTerminateContext(context.WithCancel(parent)) } + +// WithTerminate2 is similar with WithTerminate. +// But it cancels the context when it was done through parent. +func WithTerminate2(parent context.Context) TerminateContext { + return NewTerminateContext(WithCancel(parent)) +}