Lab 07: Context Package

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

The context package carries deadlines, cancellation signals, and request-scoped values across API boundaries and goroutines. It is the standard way to propagate cancellation in Go — accepted as the first argument of every function in a call chain.

Step 1: context.Background and context.TODO

These are the root contexts — empty, never cancelled.

package main

import (
    "context"
    "fmt"
)

func main() {
    // Use Background for main, init, tests, and top-level contexts
    bg := context.Background()
    fmt.Println("background:", bg)

    // Use TODO as a placeholder when unsure which context to use
    todo := context.TODO()
    fmt.Println("todo:", todo)
}

Step 2: WithCancel — Manual Cancellation

💡 Tip: Always call cancel() — defer it right after the WithCancel call. Not calling it leaks resources.

Step 3: WithTimeout — Deadline After Duration

Step 4: WithDeadline — Absolute Time Limit

Step 5: WithValue — Request-Scoped Values

💡 Tip: Use context.WithValue only for request-scoped data (trace IDs, auth tokens). Don't use it for optional function parameters.

Step 6: Propagating Cancellation Through Layers

Step 7: Context in Goroutine Cleanup

Step 8: Capstone — HTTP Handler with Context

📸 Verified Output:

Summary

Function
Use Case
Key Behaviour

context.Background()

Top-level root context

Never cancelled

context.TODO()

Placeholder during development

Never cancelled

WithCancel(ctx)

Manual cancellation

Returns ctx + cancel() func

WithTimeout(ctx, d)

Cancel after duration d

Auto-cancels after d

WithDeadline(ctx, t)

Cancel at absolute time t

Auto-cancels at t

WithValue(ctx, k, v)

Attach request-scoped data

Use unexported key types

ctx.Done()

Channel closed on cancellation

Use in select

ctx.Err()

Returns cancellation reason

context.Canceled or context.DeadlineExceeded

Last updated