11package lightning
22
3- import "strings"
3+ import (
4+ "strings"
5+ )
46
57// node is a struct that represents a node in the trie
68type node struct {
@@ -19,24 +21,13 @@ type node struct {
1921// matchChild returns the child node that matches the given part
2022func (n * node ) matchChild (part string ) * node {
2123 for _ , child := range n .Children {
22- if child .Part == part || child . IsWild {
24+ if child .Part == part {
2325 return child
2426 }
2527 }
2628 return nil
2729}
2830
29- // matchChildren returns a slice of child nodes that match the given part
30- func (n * node ) matchChildren (part string ) []* node {
31- nodes := make ([]* node , 0 )
32- for _ , child := range n .Children {
33- if child .Part == part || child .IsWild {
34- nodes = append (nodes , child )
35- }
36- }
37- return nodes
38- }
39-
4031// insert inserts a new node into the trie
4132func (n * node ) insert (pattern string , parts []string , height int , handlers []HandlerFunc ) {
4233 if len (parts ) == height {
@@ -56,20 +47,31 @@ func (n *node) insert(pattern string, parts []string, height int, handlers []Han
5647
5748// search searches the trie for a node that matches the given parts
5849func (n * node ) search (parts []string , height int ) * node {
59- if len (parts ) == height || strings . HasPrefix ( n . Part , "*" ) {
60- if n .Pattern = = "" {
61- return nil
50+ if len (parts ) == height {
51+ if n .Pattern ! = "" {
52+ return n
6253 }
63- return n
54+ return nil
6455 }
6556
6657 part := parts [height ]
67- children := n .matchChildren (part )
58+ child := n .matchChild (part )
59+
60+ // Attempt to match exact route first
61+ if child != nil {
62+ nextNode := child .search (parts , height + 1 )
63+ if nextNode != nil {
64+ return nextNode
65+ }
66+ }
6867
69- for _ , child := range children {
70- result := child .search (parts , height + 1 )
71- if result != nil {
72- return result
68+ // Attempt to match wildcard route
69+ for _ , child := range n .Children {
70+ if child .IsWild {
71+ nextNode := child .search (parts , height + 1 )
72+ if nextNode != nil {
73+ return nextNode
74+ }
7375 }
7476 }
7577
0 commit comments