MCPcopy Create free account
hub / github.com/cloud-native-go/examples / Timeout

Function Timeout

ch04/timeout.go:25–47  ·  view source on GitHub ↗
(f TimeoutFunction)

Source from the content-addressed store, hash-verified

23type WithContext func(context.Context, string) (string, error)
24
25func Timeout(f TimeoutFunction) WithContext {
26 return func(ctx context.Context, arg string) (string, error) {
27 ch := make(chan struct {
28 result string
29 err error
30 }, 1)
31
32 go func() {
33 res, err := f(arg)
34 ch <- struct {
35 result string
36 err error
37 }{res, err}
38 }()
39
40 select {
41 case res := <-ch:
42 return res.result, res.err
43 case <-ctx.Done():
44 return "", ctx.Err()
45 }
46 }
47}

Callers 2

TestTimeoutNoFunction · 0.85
TestTimeoutYesFunction · 0.85

Calls 1

ErrMethod · 0.65

Tested by 2

TestTimeoutNoFunction · 0.68
TestTimeoutYesFunction · 0.68