Home >Backend Development >Golang >How to Create a Context in Go that Doesn't Cancel?
Context management in Go provides a means to pass data between different parts of the application and handle cancellation. However, the challenge arises when you need a context that inherits the original's data but remains unaffected by its cancellation.
To address this need, Go 1.21 introduces the WithoutCancel method within the context package, which fulfills this requirement.
Alternatively, if you're using an earlier version of Go, you can create your own context implementation that's specifically designed to prevent cancellation. Here's how:
import ( "context" "time" ) type noCancel struct { ctx context.Context } func (c noCancel) Deadline() (time.Time, bool) { return time.Time{}, false } func (c noCancel) Done() <-chan struct{} { return nil } func (c noCancel) Err() error { return nil } func (c noCancel) Value(key interface{}) interface{} { return c.ctx.Value(key) } // WithoutCancel returns a context that is never canceled. func WithoutCancel(ctx context.Context) context.Context { return noCancel{ctx: ctx} }
With this custom context implementation, you can obtain a copy of the original context that:
This approach allows you to run asynchronous tasks in separate goroutines, ensuring their execution even when the parent context is terminated.
The above is the detailed content of How to Create a Context in Go that Doesn't Cancel?. For more information, please follow other related articles on the PHP Chinese website!