69 lines
1.1 KiB
Go
69 lines
1.1 KiB
Go
|
|
package routerx
|
||
|
|
|
||
|
|
import "fmt"
|
||
|
|
|
||
|
|
type Matcher func(level int) bool
|
||
|
|
|
||
|
|
type Route struct {
|
||
|
|
Index int
|
||
|
|
Name string
|
||
|
|
Match Matcher
|
||
|
|
Enabled bool
|
||
|
|
}
|
||
|
|
|
||
|
|
type Snapshot struct {
|
||
|
|
Index int
|
||
|
|
Name string
|
||
|
|
Match Matcher
|
||
|
|
}
|
||
|
|
|
||
|
|
func Normalize(routes []Route) []Snapshot {
|
||
|
|
if len(routes) == 0 {
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
result := make([]Snapshot, 0, len(routes))
|
||
|
|
for _, route := range routes {
|
||
|
|
if !route.Enabled {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
name := route.Name
|
||
|
|
if name == "" {
|
||
|
|
name = fmt.Sprintf("route-%d", route.Index)
|
||
|
|
}
|
||
|
|
match := route.Match
|
||
|
|
if match == nil {
|
||
|
|
match = MatchAllLevels()
|
||
|
|
}
|
||
|
|
result = append(result, Snapshot{
|
||
|
|
Index: route.Index,
|
||
|
|
Name: name,
|
||
|
|
Match: match,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
return result
|
||
|
|
}
|
||
|
|
|
||
|
|
func MatchAllLevels() Matcher {
|
||
|
|
return func(level int) bool {
|
||
|
|
_ = level
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func MatchLevels(levels ...int) Matcher {
|
||
|
|
levelSet := make(map[int]struct{}, len(levels))
|
||
|
|
for _, level := range levels {
|
||
|
|
levelSet[level] = struct{}{}
|
||
|
|
}
|
||
|
|
return func(level int) bool {
|
||
|
|
_, ok := levelSet[level]
|
||
|
|
return ok
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func MatchAtLeast(minLevel int) Matcher {
|
||
|
|
return func(level int) bool {
|
||
|
|
return level >= minLevel
|
||
|
|
}
|
||
|
|
}
|