feat: message parser with json/regex/text modes
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type RegexParser struct {
|
||||
re *regexp.Regexp
|
||||
}
|
||||
|
||||
func NewRegexParser(pattern string) (*RegexParser, error) {
|
||||
re, err := regexp.Compile(pattern)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("compile regex pattern: %w", err)
|
||||
}
|
||||
return &RegexParser{re: re}, nil
|
||||
}
|
||||
|
||||
func (p *RegexParser) Parse(body []byte) (*ParsedMessage, error) {
|
||||
matches := p.re.FindStringSubmatch(string(body))
|
||||
if matches == nil {
|
||||
return nil, fmt.Errorf("regex: body does not match pattern")
|
||||
}
|
||||
|
||||
names := p.re.SubexpNames()
|
||||
data := make(map[string]interface{})
|
||||
var event string
|
||||
|
||||
for i, name := range names {
|
||||
if i == 0 || name == "" {
|
||||
continue
|
||||
}
|
||||
if name == "event" {
|
||||
event = matches[i]
|
||||
} else {
|
||||
data[name] = matches[i]
|
||||
}
|
||||
}
|
||||
|
||||
return &ParsedMessage{
|
||||
Event: event,
|
||||
Data: data,
|
||||
Body: string(body),
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user