Creating a Context Copy with No Cancel Propagation in Go
When working with contexts in Go, it may arise that you need to create a copy of an existing context that contains the same values but behaves independently in terms of cancellation. This scenario occurs, for example, when you want to perform an asynchronous task after responding to an HTTP request, which may outlive the original context.
The conventional approach involves manually tracking all possible values stored in the context and creating a new context to copy those values. However, a simpler and more manageable solution is available.
Go 1.21 introduced the WithoutCancel function to the context package. This function allows you to create a new context that inherits all the values from the original context but is immune to its cancellation:
import "context" // WithoutCancel returns a context that is never canceled. func WithoutCancel(ctx context.Context) context.Context { return context.WithValue(context.Background(), context.NoCancel{}, struct{}{}) }
To use WithoutCancel, simply wrap your original context as follows:
func Handler(ctx context.Context) (interface{}, error) { result := doStuff(ctx) newContext := context.WithoutCancel(ctx) go func() { doSomethingElse(newContext) }() return result }
Now, the new goroutine will operate with a copy of the original context that won't be canceled when the original context is. This provides the flexibility and control needed in managing the lifespans of asynchronous tasks.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3