feat: add handler for communication between client and server

This commit is contained in:
2024-10-23 18:19:38 +05:30
parent 7ed1ddaa40
commit ab001490a0
2 changed files with 90 additions and 4 deletions

66
internal/lib/protocol.go Normal file
View File

@ -0,0 +1,66 @@
/*
Copyright © 2024 tux <0xtux@pm.me>
*/
package lib
import (
"bufio"
"errors"
"fmt"
"net"
"strings"
)
type Message struct {
CMD string
ARG string
}
type ProtocolHandler struct {
reader *bufio.Reader
writer *bufio.Writer
}
func InitProtocolHandler(conn net.Conn) *ProtocolHandler {
return &ProtocolHandler{
reader: bufio.NewReader(conn),
writer: bufio.NewWriter(conn),
}
}
func (p *ProtocolHandler) ReadMessage() (*Message, error) {
data, err := p.reader.ReadString('\n')
if err != nil {
return nil, err
}
cmd, arg, err := p.parseMessage(data)
if err != nil {
return nil, errors.New("can't parse data")
}
return &Message{
CMD: cmd,
ARG: arg,
}, nil
}
func (p *ProtocolHandler) WriteMessage(m *Message) error {
_, err := p.writer.WriteString(fmt.Sprintf("%s %s\n", m.CMD, m.ARG))
if err != nil {
return err
}
return p.writer.Flush()
}
func (p *ProtocolHandler) parseMessage(data string) (string, string, error) {
data = strings.TrimSpace(data)
d := strings.Fields(data)
if len(d) != 2 {
return "", "", errors.New("invalid command")
}
return d[0], d[1], nil
}