Home >Backend Development >Golang >How to Create a Context Copy in Go Without Cancel Propagation?

How to Create a Context Copy in Go Without Cancel Propagation?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 21:46:01649browse

How to Create a Context Copy in Go Without Cancel Propagation?

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.

The above is the detailed content of How to Create a Context Copy in Go Without Cancel Propagation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn