lens @ 9ba53fea71728ce64342d0d59f4199876e4b6164

 1package coroutine
 2
 3import (
 4	"context"
 5)
 6
 7// WrapProcess wraps process into a go routine and make it cancelable through context
 8func WrapProcess[V any](ctx context.Context, fun func() (V, error)) (V, error) {
 9	c := make(chan V)
10	e := make(chan error)
11	go func() {
12		defer close(c)
13		defer close(e)
14
15		v, err := fun()
16		if err != nil {
17			e <- err
18		} else {
19			c <- v
20		}
21	}()
22
23	select {
24	case <-ctx.Done():
25		var zero V
26		return zero, ctx.Err()
27	case m := <-c:
28		return m, nil
29	case err := <-e:
30		var zero V
31		return zero, err
32	}
33}