Context Timeout Wrapper

Utility for adding timeout to context-based operations

go (1.21) 2025-11-12 context timeout cancellation goroutine

Description

Helper functions for working with Go contexts and timeouts. Provides utilities for creating timeout contexts, deadline contexts, and handling context cancellation.

Features

  • Timeout context creation
  • Deadline context creation
  • Cancellation propagation
  • Timeout error handling

Code

RAW
package ctxutilimport (	"context"	"time")func WithTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {	return context.WithTimeout(parent, timeout)}func WithDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) {	return context.WithDeadline(parent, deadline)}func DoWithTimeout(ctx context.Context, timeout time.Duration, fn func(context.Context) error) error {	ctx, cancel := WithTimeout(ctx, timeout)	defer cancel()		return fn(ctx)}func IsTimeout(err error) bool {	if err == nil {		return false	}	return err == context.DeadlineExceeded || err == context.Canceled}
RAW
package mainimport (	"context"	"fmt"	"time"	"ctxutil")func main() {	ctx := context.Background()		err := ctxutil.DoWithTimeout(ctx, 5*time.Second, func(ctx context.Context) error {		// Simulate work		time.Sleep(2 * time.Second)		select {		case <-ctx.Done():			return ctx.Err()		default:			fmt.Println("Work completed")			return nil		}	})		if ctxutil.IsTimeout(err) {		fmt.Println("Operation timed out")	} else if err != nil {		fmt.Printf("Error: %v\n", err)	}}

Comments

No comments yet. Be the first to comment!