ut/deopter.go

37 lines
690 B
Go
Raw Permalink Normal View History

package ut
// Deopter describes an action that can be opted-out. This can be used in combination with defer to clean up
type Deopter interface {
Add(...DeoptFunc)
Deopt()
Invoke() error
}
// DeoptFunc describes the action signature for the Deopter.
type DeoptFunc func() error
// NewDeopter creates a deopter for the functions supplied.
func NewDeopter(fn ...DeoptFunc) Deopter {
return &deopter{fn}
}
type deopter struct {
fn []DeoptFunc
}
func (d *deopter) Add(fn ...DeoptFunc) {
d.fn = append(d.fn, fn...)
}
func (d *deopter) Deopt() {
d.fn = nil
}
func (d *deopter) Invoke() error {
var err error
for _, fn := range d.fn {
err = ErrCombine(err, fn())
}
return err
}