From 12d861c29d9a5711457d88c935b5cf5b133d319b Mon Sep 17 00:00:00 2001 From: Haibo Date: Tue, 28 Feb 2023 15:32:06 +0800 Subject: [PATCH] fix(matcher): correct matching order --- internal/matcher/middleware.go | 15 +++++++-------- internal/matcher/middleware_test.go | 16 ++++++++-------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/internal/matcher/middleware.go b/internal/matcher/middleware.go index 8d5681820..c569499ad 100644 --- a/internal/matcher/middleware.go +++ b/internal/matcher/middleware.go @@ -33,13 +33,12 @@ func (m *matcher) Use(ms ...middleware.Middleware) { func (m *matcher) Add(selector string, ms ...middleware.Middleware) { if strings.HasSuffix(selector, "*") { - selector = strings.TrimSuffix(selector, "*") - m.prefix = append(m.prefix, selector) + m.prefix = append(m.prefix, strings.TrimSuffix(selector, "*")) // sort the prefix: - // - /foo/bar // - /foo + // - /foo/bar sort.Slice(m.prefix, func(i, j int) bool { - return m.prefix[i] > m.prefix[j] + return m.prefix[i] < m.prefix[j] }) } m.matchs[selector] = ms @@ -50,13 +49,13 @@ func (m *matcher) Match(operation string) []middleware.Middleware { if len(m.defaults) > 0 { ms = append(ms, m.defaults...) } - if next, ok := m.matchs[operation]; ok { - return append(ms, next...) - } for _, prefix := range m.prefix { if strings.HasPrefix(operation, prefix) { - return append(ms, m.matchs[prefix]...) + ms = append(ms, m.matchs[prefix+"*"]...) } } + if next, ok := m.matchs[operation]; ok { + ms = append(ms, next...) + } return ms } diff --git a/internal/matcher/middleware_test.go b/internal/matcher/middleware_test.go index 9c948aebc..3ef92da00 100644 --- a/internal/matcher/middleware_test.go +++ b/internal/matcher/middleware_test.go @@ -31,10 +31,10 @@ func equal(ms []middleware.Middleware, modules ...string) bool { func TestMatcher(t *testing.T) { m := New() m.Use(logging("logging")) - m.Add("*", logging("*")) - m.Add("/foo/*", logging("foo/*")) + m.Add("/*", logging("*")) m.Add("/foo/bar/*", logging("foo/bar/*")) m.Add("/foo/bar", logging("foo/bar")) + m.Add("/foo/*", logging("foo/*")) if ms := m.Match("/"); len(ms) != 2 { t.Fatal("not equal") @@ -42,21 +42,21 @@ func TestMatcher(t *testing.T) { t.Fatal("not equal") } - if ms := m.Match("/foo/xxx"); len(ms) != 2 { + if ms := m.Match("/foo/xxx"); len(ms) != 3 { t.Fatal("not equal") - } else if !equal(ms, "logging", "foo/*") { + } else if !equal(ms, "logging", "*", "foo/*") { t.Fatal("not equal") } - if ms := m.Match("/foo/bar"); len(ms) != 2 { + if ms := m.Match("/foo/bar"); len(ms) != 4 { t.Fatal("not equal") - } else if !equal(ms, "logging", "foo/bar") { + } else if !equal(ms, "logging", "*", "foo/*", "foo/bar") { t.Fatal("not equal") } - if ms := m.Match("/foo/bar/x"); len(ms) != 2 { + if ms := m.Match("/foo/bar/x"); len(ms) != 4 { t.Fatal("not equal") - } else if !equal(ms, "logging", "foo/bar/*") { + } else if !equal(ms, "logging", "*", "foo/*", "foo/bar/*") { t.Fatal("not equal") } }