project-ely/internal/channels/timeout.go

30 lines
500 B
Go

package channels
import (
"context"
"time"
)
func RunWithTimeout(timeout time.Duration, function func() error) error {
var err error
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Launch a goroutine with a channel
finished := make(chan bool)
go func() {
err = function()
finished <- true
}()
// Then wait for completion or timeout
select {
case <-ctx.Done():
// Timed out
return ctx.Err()
case <-finished:
// Completed
}
return err
}