Go

context.Context — Cancellation & Deadlines

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`context.Context` propagates deadlines, cancellation, and request-scoped values down a call chain. EVERY blocking / long-running function should take a `ctx context.Context` as its first parameter.
Go
Raw
package main

import (
    "context"
    "fmt"
    "time"
)

func slowOperation(ctx context.Context) error {
    select {
    case <-time.After(2 * time.Second):
        fmt.Println("operation completed")
        return nil
    case <-ctx.Done():
        return ctx.Err()                       // context.DeadlineExceeded or Canceled
    }
}

func main() {
    // Cancel after 500ms — slowOperation will be told to stop
    ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
    defer cancel()                              // always defer cancel to free resources

    if err := slowOperation(ctx); err != nil {
        fmt.Println("got error:", err)          // context deadline exceeded
    }

    // Manual cancellation — cancel from elsewhere
    ctx2, cancel2 := context.WithCancel(context.Background())
    go func() { time.Sleep(100 * time.Millisecond); cancel2() }()
    if err := slowOperation(ctx2); err != nil {
        fmt.Println("got error:", err)          // context canceled
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.