From fcf545c27c70fb795a631a42738c486c07092e83 Mon Sep 17 00:00:00 2001 From: tjpcc Date: Tue, 14 Feb 2023 20:10:57 -0700 Subject: 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 --- internal/pathtree.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'internal') 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) } -- cgit v1.2.3