summaryrefslogtreecommitdiff
path: root/internal/pathtree.go
diff options
context:
space:
mode:
authortjpcc <tjp@ctrl-c.club>2023-02-14 20:10:57 -0700
committertjpcc <tjp@ctrl-c.club>2023-02-14 20:13:25 -0700
commitfcf545c27c70fb795a631a42738c486c07092e83 (patch)
treef533c819c8f4a382f796235b739f8fece0313588 /internal/pathtree.go
parent18d69173b4e23a2edd8c07c35f7a5b927587e6d7 (diff)
Router improvements.
- test coverage for Router, not just PathTree - Router.Mount() now flattens routes into the parent router - Router.Use() implemented to set middleware on a router itself
Diffstat (limited to 'internal/pathtree.go')
-rw-r--r--internal/pathtree.go48
1 files changed, 48 insertions, 0 deletions
diff --git a/internal/pathtree.go b/internal/pathtree.go
index 563e85c..7da4c2b 100644
--- a/internal/pathtree.go
+++ b/internal/pathtree.go
@@ -32,6 +32,15 @@ func (pt *PathTree[V]) Add(pattern string, value V) {
}
}
+type Route[V any] struct {
+ Pattern string
+ Value V
+}
+
+func (pt PathTree[V]) Routes() []Route[V] {
+ return pt.tree.routes()
+}
+
// pattern segment which must be a specific string ("/users/").
type segmentNode[V any] struct {
label string
@@ -216,6 +225,45 @@ func (st *subtree[V]) Add(pattern []string, value V) {
}
}
+func (st subtree[V]) routes() []Route[V] {
+ routes := []Route[V]{}
+ for _, seg := range st.segments {
+ if seg.value != nil {
+ routes = append(routes, Route[V]{
+ Pattern: seg.label,
+ Value: *seg.value,
+ })
+ }
+ for _, r := range seg.subtree.routes() {
+ r.Pattern = seg.label + "/" + r.Pattern
+ routes = append(routes, r)
+ }
+ }
+
+ for _, wc := range st.wildcards {
+ if wc.value != nil {
+ routes = append(routes, Route[V]{
+ Pattern: ":" + wc.param,
+ Value: *wc.value,
+ })
+ }
+ for _, r := range wc.subtree.routes() {
+ r.Pattern = ":" + wc.param + "/" + r.Pattern
+ routes = append(routes, r)
+ }
+ }
+
+ if st.remainder != nil {
+ rn := *st.remainder
+ routes = append(routes, Route[V]{
+ Pattern: "*" + rn.param,
+ Value: rn.value,
+ })
+ }
+
+ return routes
+}
+
type childSegments[V any] []segmentNode[V]
func (cs childSegments[V]) Len() int { return len(cs) }