我有以下代码:
//main.go
package main
import (
"edriven/events"
"fmt"
"math"
"time"
)
func main() {
fmt.Println("Starting")
events.Wg.Add(1)
go events.User.Trigger("new", "Hasan")
events.Wg.Add(1)
go events.User.Trigger("name", []any{"Hasan", "Ali"})
events.Wg.Add(1)
go events.User.Trigger("new", "Ali")
//for x := range <-events.Publish {
// fmt.Println(x)
//}
for {
select {
case x := <-events.Publish:
fmt.Println(x)
default:
fmt.Println("waiting for data ...")
time.Sleep((time.Duration(math.MaxInt64)))
}
}
}
和
//events/user.go
package events
import "fmt"
var User Events
func init() {
User.register("new", func(payload ...any) {
fmt.Println(payload[0])
//message := make(map[string]string)
//message["new"] = "done new"
Publish <- "{'new':'done'}"
Wg.Done()
})
User.register("name", func(payload ...any) {
for index, person := range payload {
fmt.Println(person, index)
}
//message := make(map[string]string)
//message["name"] = "done name"
Publish <- "{'name':'done'}" //message
Wg.Done()
})
}
和
//events/setup.go
package events
import "sync"
var Wg sync.WaitGroup
var Publish chan string
type Event struct {
Name string
Action func(...any) // <-chan string // func(...any) ([]any, error)
}
type Events struct {
handlers []Event
}
func (e *Events) register(name string, action func(...any)) {
e.handlers = append(e.handlers, Event{
Name: name,
Action: action,
})
}
func (e *Events) Trigger(name string, payload ...any) {
for _, event := range e.handlers {
if event.Name == name {
event.Action(payload)
}
}
}
我得到的输出如下,没有通过通道交换任何东西
九州编程
相关分类