From 5d613b34ee0e523f536ea8fbb55018fdd5bfe0f3 Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Tue, 5 Sep 2023 06:00:42 +0400 Subject: [PATCH] Added a newServePath() func that is a special variant of newPath that is used in ServeHTTP (it lacks an unnecessary check for * catch-all symbol). --- httpr.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/httpr.go b/httpr.go index 53dc41f..7cbaf89 100644 --- a/httpr.go +++ b/httpr.go @@ -36,9 +36,21 @@ func newPath(path string) (path, error) { return parts, nil } +// newServePath is a reduced version of newPath for ServeHTTP. +func newServePath(path string) (path, error) { + pathLen := len(path) + + if path[0] != '/' { + return nil, errors.New("path should start with a slash symbol \"/\"") + } + path = strings.ReplaceAll(path, "//", "/") - parts := strings.Split(strings.TrimSuffix(path, "/"), "/") + if path[pathLen-1] == '/' { + path = path[:pathLen-1] + } + + parts := strings.Split(path, "/") parts[0] = "/" @@ -179,7 +191,7 @@ func (rr *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - path, err := newPath(r.URL.Path) + path, err := newServePath(r.URL.Path) if err != nil { http.Error(w, err.Error(), http.StatusNotAcceptable) return