Context PackageIntermediate
1Question 1 of 1
goHow does the Context package handle cancellation, timeouts, and deadlines in Go?
Explanation & Concept
`context.Context` carries cancellation signals, deadlines, and request-scoped values across API boundaries and goroutines.
When a parent context is cancelled or times out, all child goroutines listening on `ctx.Done()` terminate immediately, preventing orphaned background leaks.
Code Example
go
package main
import (
"context"
"fmt"
"time"
)
func queryDatabase(ctx context.Context) {
select {
case <-time.After(200 * time.Millisecond):
fmt.Println("Query completed")
case <-ctx.Done():
fmt.Println("Query aborted due to timeout:", ctx.Err())
}
}
func main() {
// Cancel query if it exceeds 50ms
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
queryDatabase(ctx)
}How It Works & Key Takeaways
Using `context.WithTimeout` prevents hanging microservice calls from keeping network sockets open indefinitely.
Mock Test · 1 Questions · Optional
Ready for Interfaces & Composition?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions