通过反射,改造钩子机制

This commit is contained in:
李宇翔
2021-07-15 15:05:19 +08:00
parent d3d226f7ee
commit d7893239f2
5 changed files with 29 additions and 4 deletions

View File

@@ -83,7 +83,7 @@ func AddHookWithContext(ctx context.Context, name string, callback interface{})
func TriggerHook(name string, payload ...interface{}) { func TriggerHook(name string, payload ...interface{}) {
args := make([]reflect.Value, len(payload)) args := make([]reflect.Value, len(payload))
for i, arg := range payload { for i, arg := range payload {
args[i] = reflect.ValueOf(&arg).Elem() args[i] = reflect.ValueOf(arg)
} }
hookLocker.Lock() hookLocker.Lock()
defer hookLocker.Unlock() defer hookLocker.Unlock()

25
hook_test.go Normal file
View File

@@ -0,0 +1,25 @@
package engine
import (
"fmt"
"sync"
"testing"
"time"
)
func TestAddHook(t *testing.T) {
t.Run(t.Name(), func(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
go AddHook("test", func(a, b int) {
fmt.Printf("on test,%d,%d", a, b)
})
go AddHook("done", wg.Done)
TriggerHook("test", 2, 10)
<-time.After(time.Millisecond * 100)
TriggerHook("test", 1, 12)
<-time.After(time.Millisecond * 100)
TriggerHook("done")
wg.Wait()
})
}

View File

@@ -17,7 +17,7 @@ import (
. "github.com/logrusorgru/aurora" . "github.com/logrusorgru/aurora"
) )
const Version = "3.1.5" const Version = "3.1.6"
var ( var (
config = &struct { config = &struct {

View File

@@ -1,4 +1,4 @@
// +build linux darwin // +build linux,!arm64 darwin,!arm64
package util package util

View File

@@ -1,4 +1,4 @@
// +build linux darwin // +build linux,arm64 darwin,arm64
package util package util