Context Cancellation Propagation

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

GoResilience

Code

snippet
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)
}