Context Cancellation Propagation

Propagate cancellation and deadlines through a call tree using Go context, so abandoned work stops promptly.

GoResilience

Code

gosnippet
32 lines
package request

import (
    "context"
    "errors"
    "time"
)

var ErrTimeout = errors.New("request timed out")

type Result struct {
    Value int
    Err   error
}

func fetch(ctx context.Context, work func(context.Context) (int, error)) (int, error) {
    resultCh := make(chan Result, 1)
    go func() {
        value, err := work(ctx)
        resultCh <- Result{Value: value, Err: err}
    }()
    select {
    case <-ctx.Done():
        return 0, ErrTimeout
    case result := <-resultCh:
        return result.Value, result.Err
    }
}

func WithDeadline(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
    return context.WithTimeout(parent, timeout)
}

How the snippet works

Under the hood: the functions fetch and WithDeadline.

A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly.

Watch out for

  • Wholly standard-library — paste it in and it executes.

Applying it

The one callable in this file is func WithDeadline(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

Import WithDeadline from the file and call it — the rest of the code is implementation detail.

Statements that matter most here

func WithDeadline(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(parent, timeout)
}
resultCh <- Result{Value: value, Err: err}
var ErrTimeout = errors.New("request timed out")

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `context`, `errors`, `time`. The file defines `fetch`, `WithDeadline` at load time.