lightmux/pkg/router/pattern.go
2026-04-25 20:41:55 +00:00

77 lines
1.5 KiB
Go

package router
import (
"strings"
"git.juancwu.dev/juancwu/errx"
)
const groupOp = "router.Group"
func splitPattern(pattern string) (method, host, path string) {
rest := pattern
if i := strings.Index(pattern, " "); i >= 0 {
method = pattern[:i]
rest = strings.TrimLeft(pattern[i+1:], " ")
}
if strings.HasPrefix(rest, "/") {
return method, "", rest
}
if i := strings.Index(rest, "/"); i >= 0 {
return method, rest[:i], rest[i:]
}
return method, rest, ""
}
func validateGroupPrefix(p string) {
if p == "" {
return
}
if strings.ContainsAny(p, " \t") {
panic(errx.Newf(groupOp, "prefix must not contain whitespace (no method or host allowed): %q", p))
}
if !strings.HasPrefix(p, "/") {
panic(errx.Newf(groupOp, "prefix must start with '/': %q", p))
}
}
func normalizeGroupPrefix(p string) string {
if p == "" {
return ""
}
if len(p) > 1 && strings.HasSuffix(p, "/") {
return p[:len(p)-1]
}
if p == "/" {
return ""
}
return p
}
func joinPath(prefix, sub string) string {
if prefix == "" {
return sub
}
if sub == "" {
return prefix
}
if sub == "/" {
return prefix + "/"
}
if !strings.HasPrefix(sub, "/") {
panic(errx.Newf(groupOp, "route path must start with '/': %q", sub))
}
return prefix + sub
}
func buildPattern(method, prefix, pattern string) string {
m, host, path := splitPattern(pattern)
if method != "" {
m = method
}
full := host + joinPath(prefix, path)
if m != "" {
return m + " " + full
}
return full
}