snippetgoModeratependingCanonical
Go context pattern -- timeouts, cancellation, and request-scoped values
Viewed 0 times
contextWithTimeoutWithCancelDonegoroutine leak
go
Problem
Long-running Go operations need cancellation support and timeouts. Without context, goroutines can leak.
Solution
Use context.Context as the first parameter of any function that does I/O or could block.
Code Snippets
Context with timeout and cancellation
func fetchData(ctx context.Context, url string) ([]byte, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
return http.DefaultClient.Do(req)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
data, err := fetchData(ctx, "https://api.example.com")
if err == context.DeadlineExceeded {
fmt.Println("Timed out")
}Revisions (0)
No revisions yet.