Lesson 17 of 60 · Go
The `context` Package – Cancellation & Timeouts
Duration: 20 minutes
Context
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
context.Context carries deadlines, cancellation signals, and request‑scoped values.
func fetch(ctx context.Context, url string) ([]byte, error) {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil { return nil, err }
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
data, err := fetch(ctx, "https://example.com")
if err != nil { log.Fatal(err) }
fmt.Println(string(data))
}
Passing values via context
type key int
const requestIDKey key = 0
ctx = context.WithValue(ctx, requestIDKey, "abc-123")
id := ctx.Value(requestIDKey).(string)
Best practices
- Never store large data structures in a Context.
- Use context for cancellation and deadlines, not for passing optional parameters.