gee-web 项目中的路由注册顺序导致的 Bug

作者: FormalYou创建于 2022年11月21日更新于 2025年4月9日

We expect to get n == nil, ps == nil, but in fact, the static route pattern=/hello/b/c is matched. Due to the registration order, the route tree can be simplified as follows: [0] root: path: / [1] path: hello [2] path: :id pattern: "/hello/:id" [3] path: c pattern: "hello/b/c" The main reason is that the first registered route is /hello/:id, and the second registered route is /hello/b/c. When searching, nil is not returned. The source code is as follows:

go
func (n *node) matchChild(part string) *node {
	for _, child := range n.children {
        if child.part == part || child.isWild {  // false,  true
            // When searching for the part :id, the child is returned directly.
			return child
		}
	}
	return nil
}
func (n *node) insert(pattern string, parts []string, height int) {
	if len(parts) == height {
		n.pattern = pattern
		return
	}

    part := parts[height]
    child := n.matchChild(part) // Since the returned value is not nil, but the node whose part is ":id".
	if child == nil {
		child = &node{part: part, isWild: part[0] == ':' || part[0] == '*'}
		n.children = append(n.children, child)
	}
    
	child.insert(pattern, parts, height+1)
}

To achieve the expected result n == nil, ps == nil, we can only modify the registration order.

内容来源: geektutu/7days-golang