So I have a channel used for event processing, the main server goroutine select on this channel and call event handlers on each of the event received:
evtCh := make(chan Event)
// server loop:
for !quit {
select {
case e := <- evtCh:
handleEvent(e)
break
case quit := <-quitCh:
//finish
}
// for send a new event to processing
func addEvent(e Event) {
evtCh <- e
}
handleEvent
will call registered handlers on the event type. I have func registerEventHandler(typ EventType, func(Event))
to handle the register. This program will supports user to write extensions, that means they can register their own handlers to handle events.
Now the problem arise when in user's event handler, they might send new event to the server by calling addEvent
, this will cause the server to hang since the event handler itself is called in the context of the server's main loop(in the for loop).
How can I handle this situation elegantly? Is a queue modeled by slice a good idea?