add recorder for serial handler

This commit is contained in:
ginuerzh
2023-09-18 21:13:11 +08:00
parent a623232cc1
commit a743862f23
9 changed files with 188 additions and 26 deletions

View File

@ -12,33 +12,52 @@ import (
type recorderConn struct {
net.Conn
recorder recorder.Recorder
recorder recorder.RecorderObject
}
func (c *recorderConn) Read(b []byte) (n int, err error) {
n, err = c.Conn.Read(b)
if n > 0 && c.recorder != nil {
if n > 0 && c.recorder.Recorder != nil {
var buf bytes.Buffer
buf.WriteByte('>')
buf.WriteString(time.Now().Format("2006-01-02 15:04:05.000"))
buf.WriteByte('\n')
buf.WriteString(hex.Dump(b[:n]))
c.recorder.Record(context.Background(), buf.Bytes())
if c.recorder.Options != nil && c.recorder.Options.Direction {
buf.WriteByte('>')
}
if c.recorder.Options != nil && c.recorder.Options.TimestampFormat != "" {
buf.WriteString(time.Now().Format(c.recorder.Options.TimestampFormat))
}
if buf.Len() > 0 {
buf.WriteByte('\n')
}
if c.recorder.Options != nil && c.recorder.Options.Hexdump {
buf.WriteString(hex.Dump(b[:n]))
} else {
buf.Write(b[:n])
}
c.recorder.Recorder.Record(context.Background(), buf.Bytes())
}
return
}
func (c *recorderConn) Write(b []byte) (int, error) {
if c.recorder != nil {
if c.recorder.Recorder != nil {
var buf bytes.Buffer
buf.WriteByte('<')
buf.WriteString(time.Now().Format("2006-01-02 15:04:05.000"))
buf.WriteByte('\n')
buf.WriteString(hex.Dump(b))
c.recorder.Record(context.Background(), buf.Bytes())
if c.recorder.Options != nil && c.recorder.Options.Direction {
buf.WriteByte('<')
}
if c.recorder.Options != nil && c.recorder.Options.TimestampFormat != "" {
buf.WriteString(time.Now().Format(c.recorder.Options.TimestampFormat))
}
if buf.Len() > 0 {
buf.WriteByte('\n')
}
if c.recorder.Options != nil && c.recorder.Options.Hexdump {
buf.WriteString(hex.Dump(b))
} else {
buf.Write(b)
}
c.recorder.Recorder.Record(context.Background(), buf.Bytes())
}
return c.Conn.Write(b)
}