add EventHook

This commit is contained in:
raziman 2021-02-19 10:25:34 +08:00
parent dcce622458
commit 310a43f8cf
2 changed files with 62 additions and 0 deletions

31
hook/hook.go Normal file
View File

@ -0,0 +1,31 @@
package hook
type EventHook struct {
events map[string][]func()
}
func NewEventHook() EventHook {
return EventHook{make(map[string][]func())}
}
func (e *EventHook) AddHook(eventName string, handler func()) {
hooks, ok := e.events[eventName]
if !ok {
e.events[eventName] = []func(){handler}
}
e.events[eventName] = append(hooks, handler)
}
func (e *EventHook) RunHooks(eventName string) {
hooks, ok := e.events[eventName]
if !ok {
return
}
for _, hook := range hooks {
hook()
}
}

31
hook/hook_test.go Normal file
View File

@ -0,0 +1,31 @@
package hook
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRunHook(t *testing.T) {
h := NewEventHook()
i := 0
h.AddHook("sample", func() {
i++
})
h.AddHook("sample", func() {
i++
})
assert.Equal(t, i, 0)
h.RunHooks("x")
assert.Equal(t, i, 0)
h.RunHooks("sample")
assert.Equal(t, i, 2)
}