70 lines
1.1 KiB
Go
Raw Normal View History

2024-12-28 19:11:50 +01:00
package daemonconn
import (
"encoding/json"
"errors"
"net"
)
type Message interface {
TypeID() uint32
}
type DaemonConn struct {
FrameReadWriter
}
func FromConn(conn net.Conn) DaemonConn {
return DaemonConn{FrameReadWriter{conn}}
}
func (dc DaemonConn) ReadMessage() (Message, error) {
frame, err := dc.FrameReadWriter.ReadFrame()
if err != nil {
return nil, err
}
var msg Message
switch frame.Type() {
case MessageTypeEchoRequest:
msg, err = frameToMessage[EchoRequest](frame)
case MessageTypeEchoResponse:
msg, err = frameToMessage[EchoResponse](frame)
default:
err = errors.New("unknown frame type")
}
if err != nil {
return nil, err
}
return msg, nil
}
func (dc DaemonConn) WriteMessage(msg Message) error {
msgBytes, err := json.Marshal(msg)
if err != nil {
return err
}
f := frame{typeID: msg.TypeID(), valueBytes: msgBytes}
err = dc.WriteFrame(f)
if err != nil {
return err
}
return nil
}
func frameToMessage[M Message](frame Frame) (Message, error) {
var msg M
err := json.Unmarshal(frame.Value(), &msg)
if err != nil {
return nil, err
}
return msg, nil
}