From 3a8c5f38e824203da59a09e277e56bf961f37175 Mon Sep 17 00:00:00 2001 From: vnxme <46669194+vnxme@users.noreply.github.com> Date: Thu, 12 Sep 2024 17:48:41 +0300 Subject: [PATCH] Routing: Add regexp syntax support to UserMatcher (#3799) --- app/router/condition.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/app/router/condition.go b/app/router/condition.go index d53530e0..dc806372 100644 --- a/app/router/condition.go +++ b/app/router/condition.go @@ -192,18 +192,28 @@ func (v NetworkMatcher) Apply(ctx routing.Context) bool { } type UserMatcher struct { - user []string + user []string + pattern []*regexp.Regexp } func NewUserMatcher(users []string) *UserMatcher { usersCopy := make([]string, 0, len(users)) + patternsCopy := make([]*regexp.Regexp, 0, len(users)) for _, user := range users { if len(user) > 0 { + if len(user) > 7 && strings.HasPrefix(user, "regexp:") { + if re, err := regexp.Compile(user[7:]); err != nil { + patternsCopy = append(patternsCopy, re) + } + // Items of users slice with an invalid regexp syntax are ignored. + continue + } usersCopy = append(usersCopy, user) } } return &UserMatcher{ - user: usersCopy, + user: usersCopy, + pattern: patternsCopy, } } @@ -218,6 +228,11 @@ func (v *UserMatcher) Apply(ctx routing.Context) bool { return true } } + for _, re := range v.pattern { + if re.MatchString(user) { + return true + } + } return false }