package main
import (
"context"
"fmt"
"time"
)
func slowOperation(ctx context.Context) error {
select {
case <-time.After(2 * time.Second):
fmt.Println("operation completed")
return nil
case <-ctx.Done():
return ctx.Err() // context.DeadlineExceeded or Canceled
}
}
func main() {
// Cancel after 500ms — slowOperation will be told to stop
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel() // always defer cancel to free resources
if err := slowOperation(ctx); err != nil {
fmt.Println("got error:", err) // context deadline exceeded
}
// Manual cancellation — cancel from elsewhere
ctx2, cancel2 := context.WithCancel(context.Background())
go func() { time.Sleep(100 * time.Millisecond); cancel2() }()
if err := slowOperation(ctx2); err != nil {
fmt.Println("got error:", err) // context canceled
}
}
Create a free account and build your private vault. Share publicly whenever you want.