package main // from // https://www.ardanlabs.com/blog/2019/09/context-package-semantics-in-go.html import ( "context" "fmt" "math/rand" "time" ) func main() { // Set a duration. duration := 150 * time.Millisecond // Create a context that is both manually cancellable and will signal // cancel at the specified duration. ctx, cancel := context.WithTimeout(context.Background(), duration) defer cancel() // Create a channel to receive a signal that work is done. ch := make(chan string, 1) // Ask the goroutine to do some work for us. go func() { // Simulate work. rand.Seed(time.Now().UnixNano()) ms := rand.Intn(300) time.Sleep(time.Duration(ms) * time.Millisecond) // Report the work is done. ch <- "123" }() // Wait for the work to finish. If it takes too long, move on. select { case d := <-ch: fmt.Println("work complete", d) case <-ctx.Done(): fmt.Println("work cancelled") } }