package timeout_test import ( "sync" "testing" "time" "git.links123.net/links123.com/pkg/timeout" ) type ExcuteChan struct { c chan bool once sync.Once } func Run(limit time.Duration, f func()) bool { done := make(chan bool) go func() { f() done <- true close(done) }() select { case <-time.After(limit): return false case <-done: return true } } func Run1(limit time.Duration, f func()) bool { ec := &ExcuteChan{c: make(chan bool), once: sync.Once{}} go func() { f() ec.once.Do(func() { ec.c <- true close(ec.c) }) }() select { case <-time.After(limit): return false case <-ec.c: return true } } func TestRun(t *testing.T) { // timeout: OK if !timeout.Run(1*time.Second, func() { time.Sleep(2 * time.Second) }) { t.Log("time out: OK") } else { t.Fatal("time out: FAILED") } // timeout: FAILED if !timeout.Run(3*time.Second, func() { time.Sleep(2 * time.Second) }) { t.Log("time out: OK") } else { t.Fatal("time out: FAILED") } }