2023-02-06 22:41:54 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/gofrs/uuid/v3"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
hooker struct {
|
2023-07-14 14:15:58 +00:00
|
|
|
hooks map[string]func(any)
|
2023-02-06 22:41:54 +00:00
|
|
|
lock sync.RWMutex
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2023-07-14 14:15:58 +00:00
|
|
|
func newHooker() *hooker { return &hooker{hooks: map[string]func(any){}} }
|
2023-02-06 22:41:54 +00:00
|
|
|
|
2023-07-14 14:15:58 +00:00
|
|
|
func (h *hooker) Ping(payload any) {
|
2023-02-06 22:41:54 +00:00
|
|
|
h.lock.RLock()
|
|
|
|
defer h.lock.RUnlock()
|
|
|
|
|
|
|
|
for _, hf := range h.hooks {
|
2023-07-14 14:15:58 +00:00
|
|
|
hf(payload)
|
2023-02-06 22:41:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-14 14:15:58 +00:00
|
|
|
func (h *hooker) Register(hook func(any)) func() {
|
2023-02-06 22:41:54 +00:00
|
|
|
h.lock.Lock()
|
|
|
|
defer h.lock.Unlock()
|
|
|
|
|
|
|
|
id := uuid.Must(uuid.NewV4()).String()
|
|
|
|
h.hooks[id] = hook
|
|
|
|
|
|
|
|
return func() { h.unregister(id) }
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *hooker) unregister(id string) {
|
|
|
|
h.lock.Lock()
|
|
|
|
defer h.lock.Unlock()
|
|
|
|
|
|
|
|
delete(h.hooks, id)
|
|
|
|
}
|