Context Cancellation With Deadline

Derive a context with a deadline so downstream work is cancelled when the caller gives up, and propagate the reason through context errors.

GoResilience

Code

snippet
package main

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

func fetch(ctx context.Context, url string) (string, error) {
	select {
	case <-time.After(200 * time.Millisecond):
		return "payload from " + url, nil
	case <-ctx.Done():
		return "", ctx.Err()
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()

	result, err := fetch(ctx, "https://api.example.com/data")
	if err != nil {
		if errors.Is(err, context.DeadlineExceeded) {
			fmt.Println("deadline exceeded")
			return
		}
		panic(err)
	}
	fmt.Println(result)
}