fupie/ws/route/pattern.go

49 lines
974 B
Go

package route
import "strings"
func Pattern(v string) PartPattern {
return PartPattern(splitWithoutEmpty(v))
}
type PartPattern []string
func (p PartPattern) String() string {
return strings.Join(p, "/")
}
func (p PartPattern) Match(path string) bool {
pathParts := splitWithoutEmpty(path)
for i, part := range p {
if len(pathParts)-1 <= i {
return part == "*" || part == pathParts[i]
}
pathPart := pathParts[i]
if wildcardIndex := strings.IndexByte(part, '*'); wildcardIndex >= 0 {
if len(pathPart) < wildcardIndex || pathPart[:wildcardIndex] != part[:wildcardIndex] {
return false
}
} else if pathPart != part {
return false
}
}
return false
}
func splitWithoutEmpty(v string) []string {
out := []string{}
start := 0
for index, char := range v {
if char == '/' {
sub := v[start:index]
if len(sub) == 0 {
start++
continue
}
out = append(out, sub)
start = index + 1
}
}
return append(out, v[start:])
}