From d810d12355873d3eaf61ed3f7f0ae52db06c2c96 Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Sun, 8 Dec 2024 08:45:13 +0800 Subject: Add basic command handling --- main.go | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index 0898bd5..c320df0 100644 --- a/main.go +++ b/main.go @@ -7,10 +7,6 @@ import ( "net" ) -type Client struct { - conn net.Conn -} - func main() { listener, err := net.Listen("tcp", ":6667") if err != nil { @@ -28,6 +24,10 @@ func main() { conn: conn, } go func() { + defer func() { + client.conn.Close() + // TODO: Unified client clean-up + }() defer func() { raised := recover() if raised != nil { @@ -41,13 +41,42 @@ func main() { func (client *Client) handleConnection() { reader := bufio.NewReader(client.conn) - for { + messageLoop: for { line, err := reader.ReadString('\n') if err != nil { slog.Error("error while reading from connection", "error", err) client.conn.Close() return } - _, _ = parseIRCMsg(line) + msg, err := parseIRCMsg(line) + if err != nil { + switch (err) { + case ErrEmptyMessage: + continue messageLoop + case ErrIllegalByte: + client.Send(SMsg{Command: "ERROR", Params: []string{err.Error()}}) + break messageLoop + case ErrTagsTooLong: + fallthrough + case ErrBodyTooLong: + client.Send(SMsg{Command: ERR_INPUTTOOLONG, Params: []string{err.Error()}}) + continue messageLoop + default: + client.Send(SMsg{Command: "ERROR", Params: []string{err.Error()}}) + break messageLoop + } + } + + handler, ok := commandHandlers[msg.Command] + if !ok { + client.Send(SMsg{Command: ERR_UNKNOWNCOMMAND, Params: []string{msg.Command, "Unknown command"}}) + continue + } + + err = handler(msg, client) + if err != nil { + client.Send(SMsg{Command: "ERROR", Params: []string{err.Error()}}) + break + } } } -- cgit v1.2.3