mirror of
https://github.com/safing/portbase
synced 2025-09-04 03:29:59 +00:00
Add InjectEvent function
This commit is contained in:
parent
adcc916a6a
commit
4a4df3e134
1 changed files with 33 additions and 0 deletions
|
@ -2,6 +2,7 @@ package modules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/safing/portbase/log"
|
"github.com/safing/portbase/log"
|
||||||
|
@ -39,6 +40,38 @@ func (m *Module) processEventTrigger(event string, data interface{}) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InjectEvent triggers an event from a foreign module and executes all hook functions registered to that event.
|
||||||
|
func (m *Module) InjectEvent(sourceEventName, targetModuleName, targetEventName string, data interface{}) error {
|
||||||
|
if !m.OnlineSoon() {
|
||||||
|
return errors.New("module not yet started")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !modulesLocked.IsSet() {
|
||||||
|
return errors.New("module system not yet started")
|
||||||
|
}
|
||||||
|
|
||||||
|
targetModule, ok := modules[targetModuleName]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf(`module "%s" does not exist`, targetModuleName)
|
||||||
|
}
|
||||||
|
|
||||||
|
targetModule.eventHooksLock.RLock()
|
||||||
|
defer targetModule.eventHooksLock.RUnlock()
|
||||||
|
|
||||||
|
targetHooks, ok := targetModule.eventHooks[targetEventName]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf(`module "%s" has no event named "%s"`, targetModuleName, targetEventName)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, hook := range targetHooks {
|
||||||
|
if hook.hookingModule.OnlineSoon() {
|
||||||
|
go m.runEventHook(hook, sourceEventName, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (m *Module) runEventHook(hook *eventHook, event string, data interface{}) {
|
func (m *Module) runEventHook(hook *eventHook, event string, data interface{}) {
|
||||||
// check if source module is ready for handling
|
// check if source module is ready for handling
|
||||||
if m.Status() != StatusOnline {
|
if m.Status() != StatusOnline {
|
||||||
|
|
Loading…
Add table
Reference in a new issue