From d4565cd6f26529f465da84a6fe5afc5557961f39 Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Tue, 6 Oct 2026 13:34:26 +0200 Subject: pathrouter: add CatchAllVariableIf, VariableIf --- pathrouter/variable.go | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) (limited to 'pathrouter/variable.go') diff --git a/pathrouter/variable.go b/pathrouter/variable.go index 78bf394..386fe5e 100644 --- a/pathrouter/variable.go +++ b/pathrouter/variable.go @@ -14,10 +14,16 @@ import ( // (to be retrieved inside the request handler using [VariableValue]), // and the remaining subpath will have to be accepted by the next matcher. func Variable(name string, matcher Matcher) Matcher { - return variable(name, matcher.downcast()) + return variable(name, nil, matcher.downcast()) } -func variable(name string, matcher realMatcher) Matcher { +// VariableIf is like [Variable], but only matches if the path element is accepted by the given predicate. +// The predicate will receive the unescaped form of the path element, matching the return value of later [VariableValue] calls. +func VariableIf(name string, predicate func(string) bool, matcher Matcher) Matcher { + return variable(name, predicate, matcher.downcast()) +} + +func variable(name string, predicate func(string) bool, matcher realMatcher) Matcher { return realMatcher{ minLength: matcher.minLength + 1, maxLength: options.Map(matcher.maxLength, increment), @@ -25,11 +31,15 @@ func variable(name string, matcher realMatcher) Matcher { if len(path) == 0 || path[0] == "" { return nil } + variableValue := pathUnescape(path[0]) + if predicate != nil && !predicate(variableValue) { + return nil + } handlerFunc := matcher.accept(path[1:], rc) if handlerFunc == nil { return nil } - rc.vars[name] = pathUnescape(path[0]) + rc.vars[name] = variableValue return handlerFunc }, } -- cgit v1.3.1