project-ely/internal/channels/blocking.go

28 lines
462 B
Go

package channels
import (
"context"
)
// BlockingFunction will wait for the function to be completed
// or exit if the context is done.
func BlockingFunction(ctx context.Context, function func() error) error {
var err error
finished := make(chan bool)
go func() {
err = function()
finished <- true
}()
select {
case <-finished:
// Completed
case <-ctx.Done():
// Context closed (e.g. timed out or ctrl+c)
return ctx.Err()
}
return err
}