Ian Lance Taylor submitted this change.
net/url: preserve a trailing slash in JoinPath
Fixes #52074
Change-Id: I30897f32e70a6ca0c4e11aaf07088c27336efaba
Reviewed-on: https://go-review.googlesource.com/c/go/+/397256
Trust: Ian Lance Taylor <ia...@golang.org>
Run-TryBot: Ian Lance Taylor <ia...@golang.org>
TryBot-Result: Gopher Robot <go...@golang.org>
Reviewed-by: Matt Layher <mdla...@gmail.com>
Trust: Matt Layher <mdla...@gmail.com>
---
M src/net/url/url.go
M src/net/url/url_test.go
2 files changed, 50 insertions(+), 1 deletion(-)
diff --git a/src/net/url/url.go b/src/net/url/url.go
index bff6513..f85bdb1 100644
--- a/src/net/url/url.go
+++ b/src/net/url/url.go
@@ -1189,11 +1189,18 @@
// JoinPath returns a new URL with the provided path elements joined to
// any existing path and the resulting path cleaned of any ./ or ../ elements.
+// Any sequences of multiple / characters will be reduced to a single /.
func (u *URL) JoinPath(elem ...string) *URL {
url := *u
if len(elem) > 0 {
elem = append([]string{u.Path}, elem...)
- url.setPath(path.Join(elem...))
+ p := path.Join(elem...)
+ // path.Join will remove any trailing slashes.
+ // Preserve at least one.
+ if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") {
+ p += "/"
+ }
+ url.setPath(p)
}
return &url
}
diff --git a/src/net/url/url_test.go b/src/net/url/url_test.go
index 18aa5f8..478cc34 100644
--- a/src/net/url/url_test.go
+++ b/src/net/url/url_test.go
@@ -2099,6 +2099,31 @@
base: "http://[fe80::1%en0]:8080/",
elem: []string{"/go"},
},
+ {
+ base: "https://go.googlesource.com",
+ elem: []string{"go/"},
+ out: "https://go.googlesource.com/go/",
+ },
+ {
+ base: "https://go.googlesource.com",
+ elem: []string{"go//"},
+ out: "https://go.googlesource.com/go/",
+ },
+ {
+ base: "https://go.googlesource.com",
+ elem: nil,
+ out: "https://go.googlesource.com",
+ },
+ {
+ base: "https://go.googlesource.com/",
+ elem: nil,
+ out: "https://go.googlesource.com/",
+ },
+ {
+ base: "/",
+ elem: nil,
+ out: "/",
+ },
}
for _, tt := range tests {
wantErr := "nil"
To view, visit change 397256. To unsubscribe, or for help writing mail filters, visit settings.