Go 1 · Code patterns

Set a timeout with context

Cancel an operation if it takes longer than five seconds.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)

Official Go 1 documentation

More code patterns commands

All code patterns commands · Go 1 cheatsheet

Was this page helpful?