From cc2cd72df82ba292fb27725cf12925a5be451db5 Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Tue, 5 Sep 2023 05:58:29 +0400 Subject: [PATCH] A little optimisation of newPath() func. --- httpr.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/httpr.go b/httpr.go index c201093..53dc41f 100644 --- a/httpr.go +++ b/httpr.go @@ -9,9 +9,14 @@ import ( type path []string -// newPath splits a path and ensures that it starts with a slash (/) and doesn't -// have more than 1 catch-all parameter. +// newPath ensures that a path provided is correct and splits it. func newPath(path string) (path, error) { + pathLen := len(path) + + if pathLen == 0 { + return nil, errors.New("empty path is not allowed") + } + if path[0] != '/' { return nil, errors.New("path should start with a slash symbol \"/\"") } @@ -20,6 +25,17 @@ func newPath(path string) (path, error) { return nil, errors.New("path can have only one catch-all parameter \"*\"") } + if path[pathLen-1] == '/' { + path = path[:pathLen-1] + } + + parts := strings.Split(path, "/") + + parts[0] = "/" + + return parts, nil +} + path = strings.ReplaceAll(path, "//", "/") parts := strings.Split(strings.TrimSuffix(path, "/"), "/")