From 44b1fd4d5805b9bb77a379e1faa64c6aefdb8a34 Mon Sep 17 00:00:00 2001 From: Anthony Capirchio Date: Sat, 4 Nov 2023 23:47:29 +0100 Subject: [PATCH] Handle trailing slash --- router/tree/tree.go | 27 ++------------------------- router/tree/tree_test.go | 27 ++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/router/tree/tree.go b/router/tree/tree.go index 66d0ba7..0bb7a3e 100644 --- a/router/tree/tree.go +++ b/router/tree/tree.go @@ -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 @@ -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 @@ -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) diff --git a/router/tree/tree_test.go b/router/tree/tree_test.go index 094a889..fd593eb 100644 --- a/router/tree/tree_test.go +++ b/router/tree/tree_test.go @@ -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) +}