fix(matcher): correct matching order

pull/2690/head
Haibo 2 years ago
parent 32b1d13f90
commit 12d861c29d
  1. 15
      internal/matcher/middleware.go
  2. 16
      internal/matcher/middleware_test.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
}

@ -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")
}
}

Loading…
Cancel
Save