From e5fed1c050b1ec8a05a921f7e8c1780c106aae13 Mon Sep 17 00:00:00 2001 From: Haitao Chen Date: Tue, 28 May 2024 12:01:40 -0700 Subject: [PATCH] fix misroute when dealing multiple webservice with regex (#549) * better naming for routing related variable * extra score on regularMatchesPathToken when detectWebServices * add unittest * little tweaks * prefix each for vars in for.loop * rebase * code lint --- curly.go | 10 +++++++++- curly_test.go | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/curly.go b/curly.go index bb8d3c03..6fd2bcd5 100644 --- a/curly.go +++ b/curly.go @@ -160,7 +160,15 @@ func (c CurlyRouter) computeWebserviceScore(requestTokens []string, routeTokens if len(eachRequestToken) == 0 { return false, score } - score += 1 + score++ + + if colon := strings.Index(eachRouteToken, ":"); colon != -1 { + // match by regex + matchesToken, _ := c.regularMatchesPathToken(eachRouteToken, colon, eachRequestToken) + if matchesToken { + score++ // extra score for regex match + } + } } else { // not a parameter if eachRequestToken != eachRouteToken { diff --git a/curly_test.go b/curly_test.go index d42eed37..8a16c38c 100644 --- a/curly_test.go +++ b/curly_test.go @@ -94,6 +94,26 @@ func Test_detectWebService(t *testing.T) { } } +func Test_detectWebServiceWithRegexPath(t *testing.T) { + router := CurlyRouter{} + holaWS := new(WebService).Path("/{:hola}") + helloWS := new(WebService).Path("/{:hello}") + + var wss = []*WebService{holaWS, helloWS} + + holaJuanInTokens := tokenizePath("/hola/juan") + selected := router.detectWebService(holaJuanInTokens, wss) + if selected != holaWS { + t.Fatalf("expected holaWS, got %v", selected.rootPath) + } + + helloJuanInTokens := tokenizePath("/hello/juan") + selected = router.detectWebService(helloJuanInTokens, wss) + if selected != helloWS { + t.Fatalf("expected helloWS, got %v", selected.rootPath) + } +} + var routeMatchers = []struct { route string path string