Home >Backend Development >Golang >How to Create a Context in Go that Doesn't Cancel?

How to Create a Context in Go that Doesn't Cancel?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 06:00:03777browse

How to Create a Context in Go that Doesn't Cancel?

Circumventing Context Cancel Propagation

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:

  • Inherits all the values stored in the original context.
  • Remains active even after the original context is canceled.

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!

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