Skip to content

Commit

Permalink
Streamline usage, always use error in callback. Subscribe multiple …
Browse files Browse the repository at this point in the history
…callbacks.
  • Loading branch information
abourget committed Feb 9, 2019
1 parent e50a842 commit 10fd627
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 25 deletions.
40 changes: 16 additions & 24 deletions shutter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,27 @@ package shutter
import "sync"

type Shutter struct {
lock sync.Mutex // shutdown lock
ch chan struct{}
err error
once sync.Once
calls []func(error)
lock sync.Mutex // shutdown lock
ch chan struct{}
err error
once sync.Once
calls []func(error)
callLock sync.Mutex
}

func New(f func()) *Shutter {
func New() *Shutter {
s := &Shutter{
ch: make(chan struct{}),
}
s.SetCallback(f)
return s
}

func NewWithCallback(f func(error)) *Shutter {
s := &Shutter{
ch: make(chan struct{}),
}
s.OnShutdown(f)
return s
}

func (s *Shutter) Shutdown(err error) {
Expand Down Expand Up @@ -59,24 +67,8 @@ func (s *Shutter) IsDown() bool {
// `Shutdown()`. These calls will be blocking. It is unsafe to
// register new callbacks in multiple go-routines.
func (s *Shutter) OnShutdown(f func(error)) {
s.calls = append(s.calls, f)
}

// Deprecated: use `OnShutdown` to register a callback instead.
func (s *Shutter) SetCallback(f func()) {
s.callLock.Lock()
s.calls = []func(error){
func(_ error) {
f()
},
}
s.callLock.Unlock()
}

// Deprecated: use `OnShutdown` to register an error callback instead.
func (s *Shutter) SetErrorCallback(f func(error)) {
s.callLock.Lock()
s.calls = []func(error){f}
s.calls = append(s.calls, f)
s.callLock.Unlock()
}

Expand Down
15 changes: 14 additions & 1 deletion shutter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ func TestShutterDeadlock(t *testing.T) {
obj := struct {
*Shutter
}{}
s := New(func() {
s := NewWithCallback(func(_ error) {
obj.Shutdown(errors.New("ouch"))
})
obj.Shutter = s
Expand All @@ -20,3 +20,16 @@ func TestShutterDeadlock(t *testing.T) {

assert.Equal(t, obj.Err(), errors.New("first"))
}

func TestMultiCallbacks(t *testing.T) {
s := New()
var a int
s.OnShutdown(func(_ error) {
a++
})
s.OnShutdown(func(_ error) {
a++
})
s.Shutdown(nil)
assert.Equal(t, 2, a)
}

0 comments on commit 10fd627

Please sign in to comment.