@cryptotaxi247 / kubo / commits / ed247ec15

add do

Brian Tiger Chow committed Nov 5, 2014 at 06:45 UTC ed247ec1543168da2c64564943fec7ee7f32f687
2 files changed +57
util/do.go new
+15
@@ -0,0 +1,15 @@
1 +package util
2 +
3 +import "code.google.com/p/go.net/context"
4 +
5 +func Do(ctx context.Context, f func() error) error {
6 + ch := make(chan error)
7 + go func() { ch <- f() }()
8 + select {
9 + case <-ctx.Done():
10 + return ctx.Err()
11 + case val := <-ch:
12 + return val
13 + }
14 + return nil
15 +}
util/do_test.go new
+42
@@ -0,0 +1,42 @@
1 +package util
2 +
3 +import (
4 + "errors"
5 + "testing"
6 +
7 + "code.google.com/p/go.net/context"
8 +)
9 +
10 +func TestDoReturnsContextErr(t *testing.T) {
11 + ctx, cancel := context.WithCancel(context.Background())
12 + ch := make(chan struct{})
13 + err := Do(ctx, func() error {
14 + cancel()
15 + ch <- struct{}{} // won't return
16 + return nil
17 + })
18 + if err != ctx.Err() {
19 + t.Fail()
20 + }
21 +}
22 +
23 +func TestDoReturnsFuncError(t *testing.T) {
24 + ctx := context.Background()
25 + expected := errors.New("expected to be returned by Do")
26 + err := Do(ctx, func() error {
27 + return expected
28 + })
29 + if err != expected {
30 + t.Fail()
31 + }
32 +}
33 +
34 +func TestDoReturnsNil(t *testing.T) {
35 + ctx := context.Background()
36 + err := Do(ctx, func() error {
37 + return nil
38 + })
39 + if err != nil {
40 + t.Fail()
41 + }
42 +}