You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

56 lines
1.2 KiB

package matcher
import (
"git.diulo.com/mogfee/kit/middleware"
"sort"
"strings"
)
type Matcher interface {
Use(ms ...middleware.Middleware)
Add(selector string, ms ...middleware.Middleware)
Match(operation string) []middleware.Middleware
}
func New() Matcher {
return &matcher{
matchs: make(map[string][]middleware.Middleware),
}
}
type matcher struct {
prefix []string
defaults []middleware.Middleware
matchs map[string][]middleware.Middleware
}
func (m *matcher) Use(ms ...middleware.Middleware) {
m.defaults = ms
}
func (m *matcher) Add(selector string, ms ...middleware.Middleware) {
if strings.HasSuffix(selector, "*") {
selector = strings.TrimSuffix(selector, "*")
m.prefix = append(m.prefix, selector)
sort.Slice(m.prefix, func(i, j int) bool {
return m.prefix[i] > m.prefix[j]
})
}
m.matchs[selector] = ms
}
func (m *matcher) Match(operation string) []middleware.Middleware {
ms := make([]middleware.Middleware, 0, len(m.defaults))
if len(m.defaults) > 0 {
ms = append(ms, m.defaults...)
}
if next, ok := m.matchs[operation]; ok {
ms = append(ms, next...)
}
for _, prefix := range m.prefix {
if strings.HasPrefix(operation, prefix) {
return append(ms, m.matchs[prefix]...)
}
}
return ms
}