🚀 [Feature]: Allow optional params with route constraints (#2179)

Signed-off-by: James R T <jamestiotio@gmail.com>

Signed-off-by: James R T <jamestiotio@gmail.com>
pull/2197/head
James R T 2022-11-01 15:49:44 +08:00 committed by GitHub
parent 24a6170323
commit c63a569a92
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 4 deletions

10
path.go
View File

@ -437,10 +437,12 @@ func (routeParser *routeParser) getMatch(detectionPath, path string, params *[ma
// take over the params positions
params[paramsIterator] = path[:i]
// check constraint
for _, c := range segment.Constraints {
if matched := c.CheckConstraint(params[paramsIterator]); !matched {
return false
if !(segment.IsOptional && i == 0) {
// check constraint
for _, c := range segment.Constraints {
if matched := c.CheckConstraint(params[paramsIterator]); !matched {
return false
}
}
}

View File

@ -597,6 +597,12 @@ func Test_Path_matchParams(t *testing.T) {
{url: "/api/v1/2005-1101/paach", params: nil, match: false},
{url: "/api/v1/2005-11-01/peach", params: []string{"2005-11-01", "peach"}, match: true},
})
testCase("/api/v1/:param<int>?", []testparams{
{url: "/api/v1/entity", params: nil, match: false},
{url: "/api/v1/8728382", params: []string{"8728382"}, match: true},
{url: "/api/v1/true", params: nil, match: false},
{url: "/api/v1/", params: []string{""}, match: true},
})
}
func Test_Utils_GetTrimmedParam(t *testing.T) {
@ -851,4 +857,10 @@ func Benchmark_Path_matchParams(t *testing.B) {
{url: "/api/v1/2005-1101/paach", params: nil, match: false},
{url: "/api/v1/2005-11-01/peach", params: []string{"2005-11-01", "peach"}, match: true},
})
benchCase("/api/v1/:param<int>?", []testparams{
{url: "/api/v1/entity", params: nil, match: false},
{url: "/api/v1/8728382", params: []string{"8728382"}, match: true},
{url: "/api/v1/true", params: nil, match: false},
{url: "/api/v1/", params: []string{""}, match: true},
})
}