100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Go Context Package Cheat Sheet

Go Context Package Cheat Sheet

Creating cancelable, timeout-bound, and value-carrying contexts with context.Context for propagating deadlines and cancellation across goroutines.

1 PageIntermediateFeb 28, 2026

Creating Contexts

context.Context flows through call chains as the first parameter, conventionally named ctx.

go
ctx := context.Background()   // root context, never canceled, use in main/testsctx2 := context.TODO()          // placeholder when unsure which context to use yet// Derived, cancelable contextctx3, cancel := context.WithCancel(ctx)defer cancel()   // always call cancel to release resources, even if ctx finishes normally

Deadlines & Timeouts

WithTimeout and WithDeadline auto-cancel the context after a duration or absolute time.

go
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)resp, err := http.DefaultClient.Do(req)if err != nil {    if errors.Is(err, context.DeadlineExceeded) {        log.Println("request timed out")    }    return err}// WithDeadline: cancel at a specific absolute timedeadline := time.Now().Add(10 * time.Second)ctx2, cancel2 := context.WithDeadline(context.Background(), deadline)defer cancel2()

Respecting Cancellation in Goroutines

Long-running work must select on ctx.Done() to react to cancellation.

go
func worker(ctx context.Context, jobs <-chan int) {    for {        select {        case <-ctx.Done():            fmt.Println("worker stopping:", ctx.Err())   // context.Canceled or DeadlineExceeded            return        case job, ok := <-jobs:            if !ok {                return            }            process(job)        }    }}

Passing Request-Scoped Values

context.WithValue for request-scoped data only — never for optional function params.

go
type ctxKey stringconst requestIDKey ctxKey = "requestID"   // unexported custom type avoids collisionsfunc withRequestID(ctx context.Context, id string) context.Context {    return context.WithValue(ctx, requestIDKey, id)}func requestID(ctx context.Context) (string, bool) {    id, ok := ctx.Value(requestIDKey).(string)    return id, ok}

Context API Reference

The full public surface of the context package.

  • context.Background()- empty root context for main(), init, tests
  • context.TODO()- placeholder root context, signals 'context plumbing incomplete'
  • context.WithCancel(parent)- returns ctx + cancel func to cancel manually
  • context.WithTimeout(parent, d)- cancels automatically after duration d
  • context.WithDeadline(parent, t)- cancels automatically at absolute time t
  • context.WithValue(parent, k, v)- attaches a request-scoped key/value pair
  • ctx.Done()- channel closed when the context is canceled or times out
  • ctx.Err()- non-nil reason after Done() closes: Canceled or DeadlineExceeded
Pro Tip

Always call the cancel function returned by WithCancel/WithTimeout/WithDeadline, typically via defer cancel(), even when the operation succeeds — skipping it leaks the internal timer/goroutine until the parent context itself is canceled.

Was this cheat sheet helpful?

Explore Topics

#GoContextPackage#GoContextPackageCheatSheet#Programming#Intermediate#CreatingContexts#DeadlinesTimeouts#RespectingCancellationInGoroutines#Passing#Concurrency#CheatSheet#SkillVeris