fix(route): enhance host parsing with port suffix support

- Added logic to strip the trailing :port from the host when searching for routes.
- Updated findRouteByDomains function to ensure consistent host formatting.
- Added related tests
This commit is contained in:
yusing
2025-12-30 22:46:38 +08:00
parent e75eede332
commit 3dbbde164b
2 changed files with 51 additions and 0 deletions

View File

@@ -146,11 +146,18 @@ func findRouteAnyDomain(host string) types.HTTPRoute {
if r, ok := routes.HTTP.Get(host); ok {
return r
}
// try striping the trailing :port from the host
if before, _, ok := strings.Cut(host, ":"); ok {
if r, ok := routes.HTTP.Get(before); ok {
return r
}
}
return nil
}
func findRouteByDomains(domains []string) func(host string) types.HTTPRoute {
return func(host string) types.HTTPRoute {
host, _, _ = strings.Cut(host, ":") // strip the trailing :port
for _, domain := range domains {
if target, ok := strings.CutSuffix(host, domain); ok {
if r, ok := routes.HTTP.Get(target); ok {

View File

@@ -128,3 +128,47 @@ func TestFindRouteByDomainsExactMatch(t *testing.T) {
run(t, tests, testsNoMatch)
}
func TestFindRouteWithPort(t *testing.T) {
t.Run("AnyDomain", func(t *testing.T) {
addRoute("app1")
addRoute("app2.com")
tests := []string{
"app1:8080",
"app1.domain.com:8080",
"app2.com:8080",
}
testsNoMatch := []string{
"app11",
"app2.co",
"app2.co:8080",
}
run(t, tests, testsNoMatch)
})
t.Run("ByDomains", func(t *testing.T) {
ep.SetFindRouteDomains([]string{
".domain.com",
})
addRoute("app1")
addRoute("app2")
addRoute("app3.domain.com")
tests := []string{
"app1.domain.com:8080",
"app2:8080", // exact match fallback
"app3.domain.com:8080",
}
testsNoMatch := []string{
"app11",
"app1.domain.co",
"app1.domain.co:8080",
"app2.co",
"app2.co:8080",
"app3.domain.co",
"app3.domain.co:8080",
}
run(t, tests, testsNoMatch)
})
}