Get rid of switch-case

This commit is contained in:
Maciej Krzyżanowski 2024-12-27 14:03:55 +01:00
parent 2a7bcdd40e
commit 9c129e431b

52
main.go
View File

@ -25,6 +25,12 @@ type EchoRequest struct {
EchoByte byte EchoByte byte
} }
type MessageHandler func(m Message) error
var Handlers = map[uint32]MessageHandler{
EchoRequestID: handleEchoRequest,
}
func (EchoRequest) ID() uint32 { func (EchoRequest) ID() uint32 {
return EchoRequestID return EchoRequestID
} }
@ -36,20 +42,28 @@ func unixSocketListen() error {
} }
for conn, err := listener.Accept(); err == nil; { for conn, err := listener.Accept(); err == nil; {
handleConnection(conn) err = handleConnection(conn)
if err != nil {
slog.Error("Error handling connection:", err)
}
} }
return nil return nil
} }
func handleConnection(conn net.Conn) { func handleConnection(conn net.Conn) error {
msgChan := readSocketMessages(conn) msgChan := readSocketMessages(conn)
for msg := range msgChan { for msg := range msgChan {
handleMessage(msg) err := handleMessage(msg)
if err != nil {
return err
} }
} }
return nil
}
func readSocketMessages(conn net.Conn) chan Message { func readSocketMessages(conn net.Conn) chan Message {
msgChan := make(chan Message, 64) msgChan := make(chan Message, 64)
@ -123,15 +137,25 @@ func readMessage(conn net.Conn) ([]byte, error) {
return msgContent, nil return msgContent, nil
} }
func handleMessage(msg Message) { func handleMessage(msg Message) error {
switch msg.ID() { handler, ok := Handlers[msg.ID()]
case EchoRequestID: if !ok {
handleEchoRequest(msg.(EchoRequest)) return errors.New("message handler not defined for a given ID")
}
} }
func handleEchoRequest(req EchoRequest) { err := handler(msg)
slog.Info("Got echo request", "EchoByte", req.EchoByte) if err != nil {
return err
}
return nil
}
func handleEchoRequest(echoRequestMsg Message) error {
echoRequest := echoRequestMsg.(EchoRequest)
slog.Info("Got echo request", "EchoByte", echoRequest.EchoByte)
return nil
} }
func writeMessage(conn net.Conn, msg Message) error { func writeMessage(conn net.Conn, msg Message) error {
@ -157,13 +181,7 @@ func encodeMessage(msg Message) ([]byte, error) {
var msgJsonBytes []byte var msgJsonBytes []byte
var err error var err error
switch msg.ID() { msgJsonBytes, err = json.Marshal(msg)
case EchoRequestID:
msgJsonBytes, err = json.Marshal(msg.(EchoRequest))
default:
err = errors.New("unknown message type")
}
if err != nil { if err != nil {
return nil, err return nil, err
} }