Files
go-connfilter/filter.go

59 lines
1.8 KiB
Go
Raw Normal View History

2025-02-03 19:33:31 -05:00
package filter
import (
"bytes"
"errors"
"net"
)
var ErrInvalidFilter = errors.New("target and replacement must have the same length")
2025-02-03 19:48:35 -05:00
type ConnFilter struct {
2025-02-03 19:33:31 -05:00
net.Conn
targets []string
replacements []string
}
2025-02-03 19:48:35 -05:00
// Read reads data from the underlying connection and replaces all occurrences of target strings
// with their corresponding replacement strings. The replacements are made sequentially for each
// target-replacement pair. The modified data is then copied back to the provided buffer.
func (c *ConnFilter) Read(b []byte) (n int, err error) {
2025-02-03 19:33:31 -05:00
n, err = c.Conn.Read(b)
if err != nil {
return n, err
}
// Replace all occurrences of target with replacement
var buffer bytes.Buffer
buffer.Write(b[:n])
for i := range c.targets {
buffer.Reset()
buffer.Write(bytes.ReplaceAll(b[:n], []byte(c.targets[i]), []byte(c.replacements[i])))
}
copy(b, buffer.Bytes())
return buffer.Len(), nil
}
2025-02-03 23:33:00 -05:00
// Write writes the data to the underlying connection after replacing all occurrences of target strings
// with their corresponding replacement strings. The replacements are made sequentially for each
// target-replacement pair.
func (c *ConnFilter) Write(b []byte) (n int, err error) {
for i := range c.targets {
b = bytes.ReplaceAll(b, []byte(c.targets[i]), []byte(c.replacements[i]))
}
return c.Conn.Write(b)
}
2025-02-03 19:48:35 -05:00
// NewConnFilter creates a new ConnFilter that replaces occurrences of target strings with replacement strings in the data read from the connection.
2025-02-03 19:33:31 -05:00
// It returns an error if the lengths of target and replacement slices are not equal.
2025-02-03 21:39:04 -05:00
func NewConnFilter(parentConn net.Conn, targets, replacements []string) (net.Conn, error) {
2025-02-03 19:33:31 -05:00
if len(targets) != len(replacements) {
return nil, ErrInvalidFilter
}
2025-02-03 19:48:35 -05:00
return &ConnFilter{
2025-02-03 19:33:31 -05:00
Conn: parentConn,
targets: targets,
replacements: replacements,
}, nil
}