diff options
| author | Stefan Majewsky <majewsky@gmx.net> | 2026-10-06 13:34:26 +0200 |
|---|---|---|
| committer | Stefan Majewsky <majewsky@gmx.net> | 2026-10-06 13:34:26 +0200 |
| commit | d4565cd6f26529f465da84a6fe5afc5557961f39 (patch) | |
| tree | aebeda9fa9ab4be99aaafd5b23a94a9d0e7a76a0 /pathrouter/variable.go | |
| parent | 27d300df663ce8c1adb1aa3a54511f331bc3ae14 (diff) | |
| download | go-gg-d4565cd6f26529f465da84a6fe5afc5557961f39.tar.gz | |
pathrouter: add CatchAllVariableIf, VariableIf
Diffstat (limited to 'pathrouter/variable.go')
| -rw-r--r-- | pathrouter/variable.go | 16 |
1 files changed, 13 insertions, 3 deletions
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 }, } |
