Improved route order flexibility

This commit is contained in:
2023-07-10 14:48:28 +02:00
parent 9676708199
commit 46e1f07d6c
4 changed files with 99 additions and 5 deletions

@ -1,6 +1,8 @@
package router
import (
"fmt"
"io"
"strings"
)
@ -228,6 +230,7 @@ func (node *treeNode[T]) append(path string, data T) {
// end is called when the node was fully parsed
// and needs to decide the next control flow.
// end is only called from `tree.Add`.
func (node *treeNode[T]) end(path string, data T, i int, offset int) (*treeNode[T], int, controlFlow) {
char := path[i]
@ -250,7 +253,7 @@ func (node *treeNode[T]) end(path string, data T, i int, offset int) (*treeNode[
// node: /user/|:id
// path: /user/|:id/profile
if node.parameter != nil {
if node.parameter != nil && path[i] == parameter {
node = node.parameter
offset = i
return node, offset, controlBegin
@ -280,3 +283,47 @@ func (node *treeNode[T]) each(callback func(*treeNode[T])) {
node.wildcard.each(callback)
}
}
// PrettyPrint prints a human-readable form of the tree to the given writer.
func (node *treeNode[T]) PrettyPrint(writer io.Writer) {
node.prettyPrint(writer, -1)
}
// prettyPrint
func (node *treeNode[T]) prettyPrint(writer io.Writer, level int) {
prefix := ""
if level >= 0 {
prefix = strings.Repeat(" ", level) + "|_ "
}
switch node.kind {
case ':':
prefix += ":"
case '*':
prefix += "*"
}
fmt.Fprintf(writer, "%s%s [%v]\n", prefix, node.prefix, node.data)
for _, child := range node.children {
if child == nil {
continue
}
child.prettyPrint(writer, level+1)
}
if node.parameter != nil {
node.parameter.prettyPrint(writer, level+1)
}
if node.wildcard != nil {
node.wildcard.prettyPrint(writer, level+1)
}
}
// String returns the node prefix.
func (node *treeNode[T]) String() string {
return node.prefix
}