I wish to put a timeout on a function called foo. Consider the following
func fooWithTimeout(d time.Duration) error {
ch := make(chan error, 1)
go func() {
ch <- foo()
}()
select {
case err := <-ch:
return err
case <-time.After(d):
return errors.New("foo has timed out")
}
}
- If
foohas timed out, then willfooever be able to write to channelchor is there a risk the goroutine blocks or panics? - What happens to channel
choncefooWithTimeouthas exited? - Is this code potentially problematic?
- Should I add
defer close(ch)withingo func(){...}()just before callingfoo? - Does it matter that I use a buffered (with size 1) or an unbuffered channel in this example?