summaryrefslogtreecommitdiff
path: root/pathrouter/element.go
diff options
context:
space:
mode:
authorStefan Majewsky <majewsky@gmx.net>2026-10-06 13:45:52 +0200
committerStefan Majewsky <majewsky@gmx.net>2026-10-06 13:45:55 +0200
commit855ba5362604679f95d1ebff939f8078459486b5 (patch)
tree9d9a84000b887638f2b2c00dcf0e65b44a66875f /pathrouter/element.go
parentd4565cd6f26529f465da84a6fe5afc5557961f39 (diff)
downloadgo-gg-855ba5362604679f95d1ebff939f8078459486b5.tar.gz
pathrouter: add Elements
Diffstat (limited to 'pathrouter/element.go')
-rw-r--r--pathrouter/element.go26
1 files changed, 26 insertions, 0 deletions
diff --git a/pathrouter/element.go b/pathrouter/element.go
index 6426c04..ef56468 100644
--- a/pathrouter/element.go
+++ b/pathrouter/element.go
@@ -5,6 +5,8 @@ package pathrouter
import (
"net/http"
+ "slices"
+ "strings"
"go.xyrillian.de/gg/options"
)
@@ -12,6 +14,12 @@ import (
// Element is a [Matcher] that accepts subpaths with at least one path element.
// The first path element must be equal to the given value,
// and the remaining subpath will have to be accepted by the next matcher.
+//
+// To match a trailing slash in the request path, Element can be used with "/" as its argument:
+//
+// pathrouter.Element("/", pathrouter.Handlers(...))
+//
+// But usually, when matching request paths with trailing slashes is desired, [Here] should be used instead.
func Element(value string, matcher Matcher) Matcher {
return element(value, matcher.downcast())
}
@@ -36,3 +44,21 @@ func element(value string, matcher realMatcher) Matcher {
},
}
}
+
+// Elements is a shorthand for a chain of [Element] calls. For example,
+//
+// pathrouter.Element("v1", pathrouter.Element("admin", pathrouter.Element("warnings", innerMatcher)))
+//
+// can be shortened to
+//
+// pathrouter.Elements("v1/admin/warnings", innerMatcher)))
+//
+// Slashes in the provided value will be treated as delimiting separate path elements, so escaped slashes will not count.
+// For instance, the example above might match a request path of "/v1/admin/warnings/253", but not "/v1/admin%2Fwarnings/253".
+func Elements(value string, matcher Matcher) Matcher {
+ values := strings.Split(value, "/")
+ for _, value := range slices.Backward(values) {
+ matcher = Element(value, matcher)
+ }
+ return matcher
+}