Step Over to Go Part 16 of 50
  1. 1 Goodbye .csproj, Hello go.mod
  2. 2 The Phrasebook: C# Concepts in Go Terms
  3. 3 You Know .NET, Now Meet the Go Toolchain
  4. 4 No Enums? No Problem (Sort Of)
  5. 5 Generics: Late to the Party
  6. 6 The Million Dollar Mistake, Differently
  7. 7 Your Class Is Now a Struct (And That's Fine)
  8. 8 Where Did My Properties Go?
  9. 9 if err != nil: Your New Reality
  10. 10 Panic and Recover: The Emergency Exit
  11. 11 The switch Statement You Always Wanted
  12. 12 Stack vs Heap: Go's Escape Analysis
  13. 13 Pointers Without the Pain
  14. 14 Slices Are Not Arrays (And Neither Is List<T>)
  15. 15 Channels: The sync You Didn't Know You Wanted
  16. 16 Context Is King
  17. 17 Async/Await vs Goroutines: A Mindset Shift
  18. 18 select: Multiplexing Like a Pro
  19. 19 Mutexes and WaitGroups: When Channels Aren't the Answer
  20. 20 The Empty Interface and Type Assertions
  21. 21 Composition Over Inheritance (For Real This Time)
  22. 22 Implicit Interfaces: Scary Then Brilliant
  23. 23 Benchmarks and Profiling Out of the Box
  24. 24 Mocking in a Language Without Mockito
  25. 25 Multi-Module Repos: Monorepo Thinking
  26. 26 Organising a Real Project
  27. 27 Testing Without a Framework
  28. 28 Configuration Without IOptions<T>
  29. 29 Database Access: database/sql vs Entity Framework
  30. 30 Debugging: Delve vs Visual Studio's Comfort
  31. 31 Generate All the Things
  32. 32 GORM and Friends: When You Do Want an ORM
  33. 33 HTTP Services: net/http vs ASP.NET Core
  34. 34 JSON: Struct Tags and the Marshal Dance
  35. 35 Linting and Formatting: gofmt Is Non-Negotiable
  36. 36 Logging: slog and the Structured Logging Story
  37. 37 Shrinking Binaries and Build Tags
  38. 38 Dockerfile for Go: Simpler Than You'd Think
  39. 39 GitHub Actions for Go Projects
  40. 40 Health Checks and Readiness Probes
  41. 41 Kubernetes and Go: A Natural Fit
  42. 42 AWS Lambda and Go: Cold Starts That Don't Hurt
  43. 43 Metrics, Traces, and Logs: The OpenTelemetry Way
  44. 44 Single Binary Deploys: The Killer Feature
  45. 45 Versioning Your Modules
  46. 46 What I Actually Miss From C#
  47. 47 What I'll Never Go Back For
  48. 48 Six Months In: Was It Worth It?
  49. 49 Forty-Eight Posts on Moving From C# to Go, in the Right Order
  50. 50 Range-Over-Func Iterators for People Who Miss LINQ
About this series

Context Is King

Every Go function that does I/O, might take a while, or should be cancellable will take a context.Context as its first parameter. It's Go's answer to CancellationToken, plus request-scoped values, all in one.

If you're not using context properly, you're not writing idiomatic Go. It's that fundamental.

The Basics

func DoSomething(ctx context.Context) error {
    // Check if already cancelled
    select {
    case <-ctx.Done():
        return ctx.Err()
    default:
    }
    
    // Do work...
    return nil
}

Every context has a Done() channel that closes when the context is cancelled. You check it periodically during long operations.

Creating Contexts

Start with a background or TODO context:

ctx := context.Background()  // root context, never cancelled
ctx := context.TODO()        // placeholder when you're not sure what context to use

Then derive child contexts with cancellation or deadlines:

// Manual cancellation
ctx, cancel := context.WithCancel(parentCtx)
defer cancel()  // always call cancel to release resources

// Timeout
ctx, cancel := context.WithTimeout(parentCtx, 5*time.Second)
defer cancel()

// Deadline (absolute time)
ctx, cancel := context.WithDeadline(parentCtx, time.Now().Add(5*time.Second))
defer cancel()

When you cancel a context, all contexts derived from it are also cancelled. It's a tree.

The C# Comparison

C#'s CancellationToken:

public async Task DoSomethingAsync(CancellationToken ct)
{
    ct.ThrowIfCancellationRequested();
    
    // Do work...
}

// Usage
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await DoSomethingAsync(cts.Token);

Similar concepts:

Go C#
context.Context CancellationToken
context.WithCancel new CancellationTokenSource()
context.WithTimeout new CancellationTokenSource(TimeSpan)
ctx.Done() channel token.IsCancellationRequested
ctx.Err() token.ThrowIfCancellationRequested()
context.WithValue AsyncLocal<T> / HttpContext.Items

The big difference: Go's context also carries request-scoped values. C# separates cancellation (CancellationToken) from request-scoped data (HttpContext, AsyncLocal<T>, etc.).

Context as First Parameter

By convention, context is always the first parameter:

// CORRECT
func GetUser(ctx context.Context, id string) (*User, error)

// WRONG - context should be first
func GetUser(id string, ctx context.Context) (*User, error)

// WRONG - don't put context in structs
type UserService struct {
    ctx context.Context  // NO!
}

This convention is enforced by linters and universally followed. Don't be creative.

Proper Cancellation Checking

In long operations, check for cancellation periodically:

func ProcessItems(ctx context.Context, items []Item) error {
    for _, item := range items {
        // Check at the start of each iteration
        select {
        case <-ctx.Done():
            return ctx.Err()
        default:
        }
        
        if err := processItem(ctx, item); err != nil {
            return err
        }
    }
    return nil
}

For I/O operations, pass the context through:

func FetchData(ctx context.Context, url string) ([]byte, error) {
    req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
    if err != nil {
        return nil, err
    }
    
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err  // includes context cancellation
    }
    defer resp.Body.Close()
    
    return io.ReadAll(resp.Body)
}

When the context is cancelled, the HTTP request is aborted. Same for database queries, gRPC calls, etc.

Context Values

Context can carry request-scoped values:

type contextKey string

const userIDKey contextKey = "userID"

func WithUserID(ctx context.Context, userID string) context.Context {
    return context.WithValue(ctx, userIDKey, userID)
}

func GetUserID(ctx context.Context) (string, bool) {
    userID, ok := ctx.Value(userIDKey).(string)
    return userID, ok
}

Use sparingly! Context values should be:

  • Request-scoped data that transits process boundaries (request IDs, auth tokens)
  • Not a replacement for function parameters
// BAD: Using context to avoid passing parameters
ctx = context.WithValue(ctx, "db", database)
ctx = context.WithValue(ctx, "logger", logger)
// Now your function signatures lie about their dependencies

// GOOD: Pass dependencies explicitly, use context for request-scoped data
func HandleRequest(ctx context.Context, db *Database, logger *Logger) {
    requestID := GetRequestID(ctx)  // request-scoped, appropriate
    // ...
}

HTTP Server Context

In HTTP servers, the request carries context:

func handler(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()  // cancelled if client disconnects
    
    result, err := doExpensiveOperation(ctx)
    if err != nil {
        if errors.Is(err, context.Canceled) {
            // Client disconnected, don't bother responding
            return
        }
        http.Error(w, err.Error(), 500)
        return
    }
    
    json.NewEncoder(w).Encode(result)
}

The request context is automatically cancelled when:

  • The client closes the connection
  • The request times out
  • The server is shutting down (with proper setup)

Timeout Patterns

Setting per-operation timeouts:

func QueryWithTimeout(ctx context.Context, query string) ([]Row, error) {
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()
    
    return db.QueryContext(ctx, query)
}

The timeout is scoped to this operation. If the parent context has a shorter deadline, that wins.

// Parent has 3 second deadline
parentCtx, _ := context.WithTimeout(context.Background(), 3*time.Second)

// Child requests 5 seconds, but will actually timeout at 3
childCtx, _ := context.WithTimeout(parentCtx, 5*time.Second)

Child contexts can only be more restrictive than parents, never less.

Cancellation Propagation

When you start goroutines, propagate the context:

func ProcessInParallel(ctx context.Context, items []Item) error {
    g, ctx := errgroup.WithContext(ctx)  // from golang.org/x/sync/errgroup
    
    for _, item := range items {
        item := item
        g.Go(func() error {
            return process(ctx, item)  // same context
        })
    }
    
    return g.Wait()
}

The errgroup package creates a derived context that cancels when any goroutine returns an error. All other goroutines see the cancellation.

Common Mistakes

Don't store context in structs:

// WRONG
type Worker struct {
    ctx context.Context
}

// RIGHT: pass context to methods
func (w *Worker) Do(ctx context.Context) error

Don't use string keys for context values:

// WRONG: key collisions possible
ctx = context.WithValue(ctx, "userID", id)

// RIGHT: unexported type prevents collisions
type contextKey string
const userIDKey contextKey = "userID"

Don't ignore context cancellation:

// WRONG: ignoring cancellation
func slowOperation(ctx context.Context) {
    time.Sleep(10 * time.Second)  // doesn't respect context
}

// RIGHT: check context
func slowOperation(ctx context.Context) error {
    select {
    case <-time.After(10 * time.Second):
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

The Comparison

Aspect Go context.Context C# CancellationToken
Cancellation Yes Yes
Timeouts Yes (WithTimeout) Yes (CTS constructor)
Request values Yes (WithValue) No (use HttpContext)
First parameter convention Always Often last
Integrated with I/O Yes Yes
Tree structure Yes (parent-child) Yes (linked tokens)

The Honest Take

Context is one of Go's better patterns. It unifies cancellation and request-scoped values into one concept that permeates the ecosystem.

What Go does well:

  • Single abstraction for cancellation + deadlines + values
  • Universal convention (first parameter)
  • Clean propagation through call chains
  • Well integrated with stdlib (http, database/sql, etc.)

What C# does better:

  • Clearer separation of concerns (CancellationToken vs HttpContext)
  • CancellationToken is optional by default (overloads without it)
  • Easier to add cancellation to existing APIs
  • Less ceremony for simple cases

The verdict: Context feels heavyweight at first. Every function needs ctx context.Context as its first parameter. But the consistency pays off. You can always cancel. You can always set timeouts. You can always trace request IDs through your system.

Once you're used to it, going back to languages without pervasive cancellation support feels limiting.


That wraps up the concurrency section. Go's model is different from async/await, but it's powerful and consistent. Goroutines for concurrency, channels for communication, context for cancellation and request-scoping. Learn those three and you've got Go's concurrency story.