Skip to content

Commit

Permalink
Handle trailing slash
Browse files Browse the repository at this point in the history
  • Loading branch information
4nth0 committed Nov 4, 2023
1 parent 75d291b commit 44b1fd4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 26 deletions.
27 changes: 2 additions & 25 deletions router/tree/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func NewTree() *TreeNode {

func (t *TreeNode) AddNode(path string, method string, handler Handler) {
path = strings.TrimPrefix(path, PathDelimiter)
path = strings.TrimSuffix(path, PathDelimiter)
splitted := strings.Split(path, PathDelimiter)

currentNode := t
Expand Down Expand Up @@ -72,6 +73,7 @@ func (t *TreeNode) AddNode(path string, method string, handler Handler) {

func (t *TreeNode) GetNode(path, method string) (Handler, map[string]string, error) {
path = strings.TrimPrefix(path, PathDelimiter)
path = strings.TrimSuffix(path, PathDelimiter)
splitted := strings.Split(path, PathDelimiter)
params := map[string]string{}
currentNode := t
Expand Down Expand Up @@ -105,31 +107,6 @@ func (t *TreeNode) GetNode(path, method string) (Handler, map[string]string, err
return nil, nil, nil
}

func (t *TreeNode) RemoveNode(path string) {
path = strings.TrimPrefix(path, PathDelimiter)
splitted := strings.Split(path, PathDelimiter)

currentNode := t

for i := 0; i < len(splitted); i++ {
key := splitted[i]

if _, ok := currentNode.Childs[key]; !ok {
return
}

if i == len(splitted)-1 {
if len(currentNode.Childs[key].Childs) == 0 {
delete(currentNode.Childs, key)
} else {
currentNode.Childs[key].Handler = nil
}
return
}

currentNode = currentNode.Childs[key]
}
}
func (t *TreeNode) Dump() string {
b, _ := json.MarshalIndent(t, "", " ")
return string(b)
Expand Down
27 changes: 26 additions & 1 deletion router/tree/tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,29 @@ func TestGetNode(t *testing.T) {

}

func TestDeleteNode(t *testing.T) {}
func TestNodeWithDifferentMethods(t *testing.T) {
tree := NewTree()

tree.AddNode("/path/to/resource", "GET", DryHandler)
tree.AddNode("/path/to/resource", "POST", DryHandler)

// Vérifie la présence des deux méthodes
getHandler, _, _ := tree.GetNode("/path/to/resource", "GET")
assert.NotNil(t, getHandler)

postHandler, _, _ := tree.GetNode("/path/to/resource", "POST")
assert.NotNil(t, postHandler)
}

func TestTrailingSlash(t *testing.T) {
tree := NewTree()

tree.AddNode("/path/with/slash/", "GET", DryHandler)

// Vérifie la compatibilité avec et sans le slash final
handlerWithSlash, _, _ := tree.GetNode("/path/with/slash/", "GET")
assert.NotNil(t, handlerWithSlash)

handlerWithoutSlash, _, _ := tree.GetNode("/path/with/slash", "GET")
assert.NotNil(t, handlerWithoutSlash)
}

0 comments on commit 44b1fd4

Please sign in to comment.