A little optimisation in get() and add() methods.

This commit is contained in:
Alexander Andreev 2023-09-05 18:14:56 +04:00
parent 32e7468eef
commit 32ae3a3d0d
Signed by: Arav
GPG Key ID: D22A817D95815393

View File

@ -89,7 +89,9 @@ outer:
path[i] = curNode.endpoint + ":" + path[i]
}
if pathLen == i+1 {
pathNextIdx := i + 1
if pathLen == pathNextIdx {
var params Params = make(Params)
for _, part := range path {
@ -102,14 +104,15 @@ outer:
return curNode.handler, params
}
if pathLen > i+1 {
var paramNode *node
if pathLen > pathNextIdx {
if len(curNode.children) == 0 {
break outer
}
var paramNode *node
for _, next := range curNode.children {
if next.endpoint == path[i+1] {
if next.endpoint == path[pathNextIdx] {
curNode = next
continue outer
}
@ -132,12 +135,12 @@ outer:
}
func (n *node) add(path path, handler http.HandlerFunc) error {
pathLen := len(path)
pathLastIdx := len(path) - 1
curNode := n
outer:
for i := range path {
if pathLen == i+1 {
if pathLastIdx == i {
if curNode.handler != nil {
return errors.New("attempt to redefine a handler for already existing path")
}
@ -146,27 +149,29 @@ outer:
return nil
}
pathNextIdx := i + 1
for _, child := range curNode.children {
firstChar := path[i+1][0]
firstChar := path[pathNextIdx][0]
if (firstChar == ':' || firstChar == '*') && firstChar == child.endpoint[0] {
// Do not allow different param names, because only the first one
// is saved, so a param won't be available by a new name.
// Therefore, it is good to return an error because in this case
// you're doing something wrong.
if path[i+1] != child.endpoint {
return errors.New("param names " + path[i+1] + " and " + child.endpoint + " are differ")
if path[pathNextIdx] != child.endpoint {
return errors.New("param names " + path[pathNextIdx] + " and " + child.endpoint + " are differ")
}
curNode = child
continue outer
}
if child.endpoint == path[i+1] {
if child.endpoint == path[pathNextIdx] {
curNode = child
continue outer
}
}
newChild := &node{endpoint: path[i+1]}
newChild := &node{endpoint: path[pathNextIdx]}
curNode.children = append(curNode.children, newChild)
curNode = newChild
}