Context and timeouts
Use context to cancel work, time out HTTP requests and avoid leaking goroutines.
- Pass context.Context to operations that can be cancelled or timed out.
- Always call the cancel function returned by WithTimeout or WithCancel.
- Put a timeout on HTTP requests using http.NewRequestWithContext.
- Never start a goroutine without a way for it to stop.
In plain English
A goroutine is a lightweight function that runs at the same time as other goroutines, and if it never finishes it becomes a leak that holds memory. A context.Context carries cancellation and deadline information through a call, so long work can stop when it is no longer needed. context.WithTimeout returns a context that cancels itself after a duration, and you call the returned cancel function to clean it up early. Passing a context into an HTTP request lets a slow server or client be cut off instead of waiting forever.
Step by step
- 1Start with context.Background and wrap it with WithTimeout.
- 2Pass the context into the function that does the work.
- 3Call the cancel function with defer so the timer is cleaned up.
- 4Attach the context to HTTP requests with http.NewRequestWithContext.
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func fetch(ctx context.Context, url string) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
fmt.Println(url, resp.StatusCode)
return nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := fetch(ctx, "https://example.com"); err != nil {
fmt.Println(err)
}
}Common mistakes
- Forgetting to call cancel leaks the timer and the context until it eventually fires.
- Starting a goroutine that blocks on a channel with no sender leaks the goroutine forever.
- Using an HTTP request without a context lets a slow endpoint hang your program.
- Creating a context and discarding the cancel function is wrong, because that function is how you stop early.
Apply a timeout
Write a function run that creates a context with a 3-second timeout, calls work(ctx), and always calls the cancel function.
func run() {
ctx := context.Background()
work(ctx)
}Why pass a context.Context to a long-running operation?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.