context.Context
What is it?
`context.Context` is a standard way to carry:
across API boundaries and between goroutines.
What is it used for?
Cancel work when a request is no longer needed (client disconnected, timeout, shutdown).
Enforce timeouts/deadlines for I/O (HTTP calls, DB queries, RPC).
Pass request-scoped metadata (trace IDs, request IDs) carefully.
Core functions
`context.Background()` — root context for main/service.
`context.TODO()` — placeholder when you don’t have a context yet.
`context.WithCancel(parent)` — manual cancellation.
`context.WithTimeout(parent, d)` — cancel after duration.
`context.WithDeadline(parent, t)` — cancel at specific time.
`context.WithValue(parent, key, val)` — attach request-scoped values (use sparingly).
Example: timeout for work
package main
import (
"context"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = ctx // pass ctx into HTTP/DB/RPC calls
}
Example: cancellation (stop goroutine)
package main
import (
"context"
"time"
)
func worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
time.Sleep(10 * time.Millisecond)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
go worker(ctx)
time.Sleep(50 * time.Millisecond)
cancel()
time.Sleep(20 * time.Millisecond)
}
Notes / pitfalls
Context is NOT for global configuration.
Do NOT store large values in context; keep values small (IDs).
Use typed keys to avoid collisions.
Always call `cancel()` to release resources (timers) for timeout/deadline contexts.
Related pages
Hard words (English)
deadline /ˈdedlaɪn/: hạn chót
cancellation /ˌkænsəˈleɪʃən/: huỷ
signal /ˈsɪɡnəl/: tín hiệu
request-scoped /rɪˈkwest skoʊpt/: gắn với 1 request
metadata /ˈmetəˌdeɪtə/: dữ liệu mô tả
API boundary /ˌeɪ piː ˈaɪ ˈbaʊndri/: ranh giới
API
collision /kəˈlɪʒən/: xung đột
sparingly /ˈsperɪŋli/: dùng hạn chế