Documentation
¶
Overview ¶
Package msgmux provides a message multiplexer. It can be used to dispatch and handle any kind of message such as events and commands.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type DispatchMux ¶
type DispatchMux struct {
// contains filtered or unexported fields
}
DispatchMux is a message multiplexer.
Example ¶
package main import ( "fmt" "github.com/uudashr/msgmux" ) func main() { type CancelOrder struct { OrderID string Reason string } type OrderCompleted struct { OrderID string } mux := msgmux.NewDispatchMux() mux.Handle(func(e CancelOrder) error { fmt.Printf("CancelOrder{OrderID:%s Reason:%s}\n", e.OrderID, e.Reason) return nil }) mux.Handle(func(e OrderCompleted) error { fmt.Printf("OrderCompleted{OrderID:%s}\n", e.OrderID) return nil }) mux.Dispatch(CancelOrder{ OrderID: "order-123", Reason: "Change my mind", }) mux.Dispatch(OrderCompleted{ OrderID: "order-123", }) }
Output: CancelOrder{OrderID:order-123 Reason:Change my mind} OrderCompleted{OrderID:order-123}
func NewDispatchMux ¶
func NewDispatchMux() *DispatchMux
NewDispatchMux allocates and returns a new DispatchMux.
func (*DispatchMux) Dispatch ¶
func (m *DispatchMux) Dispatch(msg Message) error
Dispatch dispatches the message.
A shorthand of DispatchMux.DispatchContext with context.Background.
func (*DispatchMux) DispatchContext ¶
func (m *DispatchMux) DispatchContext(ctx context.Context, msg Message) error
DispatchContext dispatches the message.
The msg need to be a valid Message, otherwise it will return an error.
func (*DispatchMux) Handle ¶
func (m *DispatchMux) Handle(fn MessageHandler)
Handle registers a fn as handler for the specific message type.
The fn need to be valid MessageHandler, otherwise it will panic. Multiple registrations for the same message type is not allowed and will cause a panic.
type Message ¶
type Message any
Message represents a specific message. It must be a struct type.
Example:
type CancelOrder struct { OrderID string Reason string } type OrderCompleted struct { OrderID string }
type MessageHandler ¶
type MessageHandler any
MssageHandler is a function type to handle the messages.
The form of function is:
func(msg Message) error
or with context.Context parameter:
func(ctx context.Context, msg Message) error
where the Message represents a specific message type (struct).
Example:
mux := msgmux.NewDispatchMux() mux.Handle(func(event OrderCompleted) error { // handle the event return nil })