]> Cypherpunks repositories - gostls13.git/commitdiff
net/url: preserve a trailing slash in JoinPath
authorIan Lance Taylor <iant@golang.org>
Thu, 31 Mar 2022 20:21:39 +0000 (13:21 -0700)
committerIan Lance Taylor <iant@golang.org>
Tue, 5 Apr 2022 22:09:11 +0000 (22:09 +0000)
Fixes #52074

Change-Id: I30897f32e70a6ca0c4e11aaf07088c27336efaba
Reviewed-on: https://go-review.googlesource.com/c/go/+/397256
Trust: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Matt Layher <mdlayher@gmail.com>
Trust: Matt Layher <mdlayher@gmail.com>

src/net/url/url.go
src/net/url/url_test.go

index bff6513b85fc039a3926a18e6f41b38dc10d1847..f85bdb15804352901760ae60a7b75640f36381a0 100644 (file)
@@ -1189,11 +1189,18 @@ func (u *URL) UnmarshalBinary(text []byte) error {
 
 // 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
 }
index 18aa5f8a1c55a8abcdac3839bab3c559eb2cb3e4..478cc34872700419ac3607a5cf53f6e2426e5aee 100644 (file)
@@ -2099,6 +2099,31 @@ func TestJoinPath(t *testing.T) {
                        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"