diff --git a/pkg/apigw/filter/prefilter_test.go b/pkg/apigw/filter/prefilter_test.go index 315b644e5..24eba8c71 100644 --- a/pkg/apigw/filter/prefilter_test.go +++ b/pkg/apigw/filter/prefilter_test.go @@ -43,6 +43,11 @@ func Test_header(t *testing.T) { headers: map[string][]string{"Foo": {"bar"}}, err: "could not validate headers: failed to select 'Foo1' on *expr.Vars: no such key 'Foo1'", }, + { + name: "regex matching key", + expr: `{"expr":"match(Foo, \"^b\\\\wr\\\\s.*$\")"}`, + headers: map[string][]string{"Foo": {"bar "}}, + }, // { // name: "matching header with hyphen - TODO", // expr: `{"expr":"Content-type == \"application/json\""}`, diff --git a/pkg/expr/func_str.go b/pkg/expr/func_str.go index 76bede31f..6b3ae7080 100644 --- a/pkg/expr/func_str.go +++ b/pkg/expr/func_str.go @@ -3,11 +3,12 @@ package expr import ( "errors" "fmt" - "github.com/spf13/cast" "reflect" "regexp" "strings" + "github.com/spf13/cast" + "github.com/PaesslerAG/gval" valid "github.com/asaskevich/govalidator" ) @@ -37,6 +38,7 @@ func StringFunctions() []gval.Language { gvalFunc("shorten", shorten), gval.Function("camelize", camelize), gval.Function("snakify", snakify), + gval.Function("match", match), } } @@ -198,3 +200,21 @@ func camelize(s string) string { func snakify(s string) string { return strings.ToLower(strings.Replace(strings.Title(s), " ", "_", -1)) } + +func match(s string, regex interface{}) (b bool, err error) { + var ( + r *regexp.Regexp + ) + + switch v := regex.(type) { + case *regexp.Regexp: + r = v + case string: + if r, err = regexp.Compile(v); err != nil { + return + } + } + + b = r.MatchString(s) + return +} diff --git a/pkg/expr/func_str_test.go b/pkg/expr/func_str_test.go index 85cbeadd7..b53d834f7 100644 --- a/pkg/expr/func_str_test.go +++ b/pkg/expr/func_str_test.go @@ -189,3 +189,10 @@ func Example_substring_endOverflow() { // output: // o bar baz_test } + +func Example_match() { + eval(`match("foo bar baz_test", "^foo\\s.*$")`, nil) + + // output: + // true +}