diff options
Diffstat (limited to 'internal')
-rw-r--r-- | internal/pathtree.go | 48 |
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) } |