aboutsummaryrefslogtreecommitdiff
path: root/pkg/coroutine/coroutine.go
diff options
context:
space:
mode:
Diffstat (limited to 'pkg/coroutine/coroutine.go')
-rw-r--r--pkg/coroutine/coroutine.go33
1 files changed, 33 insertions, 0 deletions
diff --git a/pkg/coroutine/coroutine.go b/pkg/coroutine/coroutine.go
new file mode 100644
index 0000000..96d149e
--- /dev/null
+++ b/pkg/coroutine/coroutine.go
@@ -0,0 +1,33 @@
+package coroutine
+
+import (
+ "context"
+)
+
+// WrapProcess wraps process into a go routine and make it cancelable through context
+func WrapProcess[V any](ctx context.Context, fun func() (V, error)) (V, error) {
+ c := make(chan V)
+ e := make(chan error)
+ go func() {
+ defer close(c)
+ defer close(e)
+
+ v, err := fun()
+ if err != nil {
+ e <- err
+ } else {
+ c <- v
+ }
+ }()
+
+ select {
+ case <-ctx.Done():
+ var zero V
+ return zero, ctx.Err()
+ case m := <-c:
+ return m, nil
+ case err := <-e:
+ var zero V
+ return zero, err
+ }
+}