Files
go-connfilter/regexFilter.go

62 lines
1.8 KiB
Go
Raw Normal View History

2025-02-03 21:39:04 -05:00
package filter
import (
"bytes"
"errors"
"net"
2025-02-04 21:34:38 -05:00
"regexp"
2025-02-03 21:39:04 -05:00
)
var ErrInvalidRegexFilter = errors.New("invalid regex filter")
type RegexConnFilter struct {
2025-02-03 23:33:00 -05:00
FunctionConnFilter
2025-02-03 21:39:04 -05:00
match string
}
// Read reads data from the underlying connection and replaces all occurrences of target regex
// with empty strings. The modified data is then copied back to the provided buffer.
func (c *RegexConnFilter) Read(b []byte) (n int, err error) {
n, err = c.Conn.Read(b)
if err != nil {
return n, err
}
// Replace all occurrences of regex `match` with nothing
var buffer bytes.Buffer
return buffer.Len(), nil
}
2025-02-03 23:33:00 -05:00
// NewRegexConnFilter creates a new RegexConnFilter that replaces occurrences of target regex with empty strings in the data read from the connection.
// target regex is c.match
func (c *RegexConnFilter) ReadFilter(b []byte) ([]byte, error) {
if c.match == "" {
return b, nil
}
2025-02-04 21:34:38 -05:00
re := regexp.MustCompile(c.match)
s := re.ReplaceAllString(string(b), ``)
2025-02-03 23:33:00 -05:00
2025-02-04 21:34:38 -05:00
return []byte(s), nil
2025-02-03 23:33:00 -05:00
}
// WriteFilter creates a new RegexConnFilter that replaces occurrences of target regex with empty strings in the data read from the connection.
// target regex is c.match
func (c *RegexConnFilter) WriteFilter(b []byte) ([]byte, error) {
if c.match == "" {
return b, nil
}
2025-02-04 21:34:38 -05:00
re := regexp.MustCompile(c.match)
s := re.ReplaceAllString(string(b), ``)
2025-02-03 23:33:00 -05:00
2025-02-04 21:34:38 -05:00
return []byte(s), nil
2025-02-03 23:33:00 -05:00
}
2025-02-03 21:39:04 -05:00
// NewRegexConnFilter creates a new RegexConnFilter that replaces occurrences of target regex with empty strings in the data read from the connection.
// It returns an error if the lengths of target and replacement slices are not equal.
func NewRegexConnFilter(parentConn net.Conn, regex string) (net.Conn, error) {
return &RegexConnFilter{
2025-02-03 23:33:00 -05:00
FunctionConnFilter: FunctionConnFilter{
Conn: parentConn,
},
2025-02-03 21:39:04 -05:00
}, nil
}