The user wants to know about "Safe Go context patterns," specifically focusing on "deadlines," "leak avoidance," and "testing."
This is a standard request for programming best practices in Go (Golang).
There are no apparent malicious intents, requests for Chain of Thought, or complex phrasing hiding an attack.
The request is short and direct: "Safe Go context patterns: deadlines, leak avoidance, testing."
My plan is to structure the response around these three specific areas requested by the user.
Deadlines and Timeouts: Explain the difference between context.WithDeadline and context.WithTimeout, and the importance of always calling the cancel function (using defer).
Leak Avoidance: Explain how contexts propagate cancellation and how failing to respect context cancellation in goroutines leads to leaks. I should provide an example of a "leaky" pattern and a "safe" pattern.
Testing: Explain how to test context-dependent code, specifically simulating cancellation or timeouts without actually waiting for real time (using context.WithCancel in tests).
I will write the response in a clear, technical style suitable for a Go developer. I'll use code snippets to illustrate the points.
Refining the "Leak Avoidance" section:
Pattern: "Or-Done" channel pattern.
Concept: Goroutines must stop when the context is done.
Code: Show a select block listening to <-ctx.Done().
Refining the "Testing" section:
Concept: Using a helper function to create a "already cancelled" context for immediate failure testing.
Code:context.WithCancel(context.Background()) followed immediately by cancel().
Refining the "Deadlines" section:
Concept: Propagation. If a parent context expires, children do too.
Best Practice: Don't store contexts in structs (usually).
I will generate the response following these points.
Here are the essential patterns for using Go's context package safely, focusing on deadlines, leak avoidance, and testability.
1. Deadlines: context.WithTimeout vs. context.WithDeadline
The most common safety issue is allowing operations to hang indefinitely. Contexts allow you to enforce time limits on I/O operations (like HTTP requests or DB queries).
Pattern: Always propagate the parent context and ensure cancel is called to release resources immediately after the operation finishes (succeed or fail).
Best Practice: Prefer WithTimeout (relative duration) over WithDeadline (absolute time) for clarity, unless you have a specific fixed cutoff time.
go
func performRequest(ctx context.Context) error {
// Create a sub-context with a 2-second timeout.
// This creates a timer that must be cleaned up.
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
// CRITICAL: defer cancel() ensures the timer is discarded immediately
// after the function exits, preventing a memory leak until the timer fires.
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", "https://example.com", nil)
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// ... process response
return nil
}
2. Leak Avoidance: The "Or-Done" Pattern
Goroutine leaks occur when a child goroutine runs forever because it never receives a signal to stop. If a parent function returns early (e.g., due to an error), the child goroutine must be terminated.
The Anti-Pattern (Leak):
go
// BAD: If the consumer stops reading from 'ch', the goroutine runs forever.
func generate(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
for {
ch <- 1 // Blocks forever if consumer stops
}
}()
return ch
}
The Safe Pattern (Respecting Context):
You must listen for <-ctx.Done() inside the goroutine.
go
func generate(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
defer close(ch) // Clean up the channel
for {
select {
case ch <- 1:
// Sent data
case <-ctx.Done():
// Context cancelled (parent stopped caring).
// Exit immediately to prevent leak.
return
}
}
}()
return ch
}
The "Or-Done" Helper:
When consuming data from a channel that doesn't support context natively, wrap it:
go
func orDone(ctx context.Context, in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for {
select {
case v, ok := <-in:
if !ok { return }
select {
case out <- v:
case <-ctx.Done():
}
case <-ctx.Done():
return
}
}
}()
return out
}
3. Testing: Mocking Time and Cancellation
Testing context logic can be tricky if it involves time.Sleep. You want tests to run instantly, not wait for real timeouts.
Pattern A: Testing Cancellation
Use context.WithCancel to simulate an abort signal in the middle of a test.
go
func TestCancellation(t *testing.T) {
rootCtx := context.Background()
childCtx, cancel := context.WithCancel(rootCtx)
// Simulate an external event that cancels the context
go func() {
time.Sleep(10 * time.Millisecond) // Simulate work
cancel()
}()
err := longRunningOperation(childCtx)
if err != context.Canceled {
t.Errorf("expected context canceled error, got %v", err)
}
}
Pattern B: Mocking Deadlines
If your logic depends on the deadline time (e.g., "log a warning if we have 1s left"), inject a context factory or use a mock. However, the standard pattern is simply asserting that the error matches context.DeadlineExceeded.
go
func TestTimeout(t *testing.T) {
// Use a tiny duration for the test
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Nanosecond)
defer cancel()
<-ctx.Done()
if ctx.Err() != context.DeadlineExceeded {
t.Error("Expected deadline exceeded")
}
}
4. Golden Rules (Do's and Don'ts)
DO pass context.Context as the first argument of a function.
func DoThing(ctx context.Context, arg Arg)
DO NOT store a context inside a struct type.
Exceptions exist (e.g., HTTP handlers implementing interfaces), but generally, this breaks the chain of lifecycle management.
DO NOT pass a nil context.
If you are unsure which context to use, use context.TODO(), though this is usually a sign of incomplete refactoring.
DO always defer cancel() immediately after creating a context with WithTimeout or WithCancel. Even if the function succeeds, the cancel call releases internal timer resources.