Use context.WithTimeout to create a deadline-aware context and pass it to your operations to enforce a timeout. This pattern ensures that long-running operations are cancelled automatically if they exceed the specified duration.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Pass ctx to your function instead of context.Background()
result, err := myFunction(ctx)
if err == context.DeadlineExceeded {
// Handle timeout
}