ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() select { case <-ctx.Done(): fmt.Println("Timeout or cancellation") case <-someLongRunningOperation(): fmt.Println("Operation completed") }
ctx, cancel := context.WithCancel(context.Background()) go func() { time.Sleep(5*time.Second) cancel() // cancel the context after 5 seconds }() select { case <-ctx.Done(): fmt.Println("Context was cancelled") case <-someLongRunningOperation(): fmt.Println("Operation completed") }This code creates a new context with cancellation and defers its cancellation. It then runs a goroutine that cancels the context after 5 seconds. It waits for either the context to be cancelled, or the long-running operation to complete. The "golang.org/x/net/context" package is now deprecated in favor of the "context" package from the standard library (starting from Go 1.7).