Skip to content

Instantly share code, notes, and snippets.

@fatihtatoglu
Created May 28, 2023 09:36
Show Gist options
  • Save fatihtatoglu/f5b35243e4de58b4d0d17d607d707b42 to your computer and use it in GitHub Desktop.
Save fatihtatoglu/f5b35243e4de58b4d0d17d607d707b42 to your computer and use it in GitHub Desktop.
Command & Event with Handlers
package main
import (
"encoding/json"
"fmt"
"log"
)
// Command represents an action to be performed by the server.
type Command struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
// Event represents something that has occurred or changed in the system.
type Event struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
// CommandHandler is responsible for processing commands.
type CommandHandler interface {
HandleCommand(cmd Command)
}
// EventHandler is responsible for reacting to events.
type EventHandler interface {
HandleEvent(evt Event)
}
// SampleCommandHandler is an example command handler implementation.
type SampleCommandHandler struct{}
func (h *SampleCommandHandler) HandleCommand(cmd Command) {
fmt.Println("Handling command:", cmd.Type)
// Process the command and perform necessary actions
}
// SampleEventHandler is an example event handler implementation.
type SampleEventHandler struct{}
func (h *SampleEventHandler) HandleEvent(evt Event) {
fmt.Println("Handling event:", evt.Type)
// React to the event and update the application state
}
// CommandRegistry maps command types to their corresponding handlers.
var CommandRegistry = map[string]CommandHandler{
"CommandTypeA": &SampleCommandHandler{},
}
// EventRegistry maps event types to their corresponding handlers.
var EventRegistry = map[string]EventHandler{
"EventTypeX": &SampleEventHandler{},
}
// ProcessCommand processes a command by dispatching it to the appropriate handler.
func ProcessCommand(cmd Command) {
handler, exists := CommandRegistry[cmd.Type]
if !exists {
log.Println("No handler registered for command type:", cmd.Type)
return
}
handler.HandleCommand(cmd)
}
// ProcessEvent processes an event by dispatching it to the appropriate handler.
func ProcessEvent(evt Event) {
handler, exists := EventRegistry[evt.Type]
if !exists {
log.Println("No handler registered for event type:", evt.Type)
return
}
handler.HandleEvent(evt)
}
func main() {
// Sample usage
cmdData := `{"type": "CommandTypeA", "data": {"key": "value"}}`
evtData := `{"type": "EventTypeX", "data": {"key": "value"}}`
var cmd Command
if err := json.Unmarshal([]byte(cmdData), &cmd); err != nil {
log.Fatal("Failed to unmarshal command:", err)
}
var evt Event
if err := json.Unmarshal([]byte(evtData), &evt); err != nil {
log.Fatal("Failed to unmarshal event:", err)
}
ProcessCommand(cmd)
ProcessEvent(evt)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment