Go
Beginner
1 min read
Context for Cancellation and Timeouts
Example
package main
import (
"context"
"fmt"
"time"
)
func doWork(ctx context.Context, id int) error {
select {
case <-time.After(200 * time.Millisecond):
fmt.Printf("worker %d finished\n", id)
return nil
case <-ctx.Done():
fmt.Printf("worker %d cancelled: %v\n", id, ctx.Err())
return ctx.Err()
}
}
func fetchData(ctx context.Context, url string) (string, error) {
// simulate a slow network request
select {
case <-time.After(500 * time.Millisecond):
return "data from " + url, nil
case <-ctx.Done():
return "", fmt.Errorf("fetch %s: %w", url, ctx.Err())
}
}
func main() {
// WithCancel — manual cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(100 * time.Millisecond)
cancel() // cancel after 100ms
}()
doWork(ctx, 1)
// WithTimeout — automatic cancellation
ctx2, cancel2 := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel2()
data, err := fetchData(ctx2, "https://example.com")
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("received:", data)
}
}