Use ResolveReference instead of path.Join (#4073)

Signed-off-by: Jonas Franz <info@jonasfranz.software>
This commit is contained in:
Jonas Franz 2018-05-29 18:12:04 +02:00 committed by techknowlogick
parent d1954ae4e7
commit 1177a19a5b
2 changed files with 17 additions and 6 deletions

View file

@ -114,16 +114,25 @@ func cutoutVerbosePrefix(prefix string) string {
// URLJoin joins url components, like path.Join, but preserving contents // URLJoin joins url components, like path.Join, but preserving contents
func URLJoin(base string, elems ...string) string { func URLJoin(base string, elems ...string) string {
u, err := url.Parse(base) if !strings.HasSuffix(base, "/") {
base += "/"
}
baseURL, err := url.Parse(base)
if err != nil { if err != nil {
log.Error(4, "URLJoin: Invalid base URL %s", base) log.Error(4, "URLJoin: Invalid base URL %s", base)
return "" return ""
} }
joinArgs := make([]string, 0, len(elems)+1) joinedPath := path.Join(elems...)
joinArgs = append(joinArgs, u.Path) argURL, err := url.Parse(joinedPath)
joinArgs = append(joinArgs, elems...) if err != nil {
u.Path = path.Join(joinArgs...) log.Error(4, "URLJoin: Invalid arg %s", joinedPath)
return u.String() return ""
}
joinedURL := baseURL.ResolveReference(argURL).String()
if !baseURL.IsAbs() {
return joinedURL[1:] // Removing leading '/'
}
return joinedURL
} }
// RenderIssueIndexPatternOptions options for RenderIssueIndexPattern function // RenderIssueIndexPatternOptions options for RenderIssueIndexPattern function

View file

@ -83,6 +83,8 @@ func TestURLJoin(t *testing.T) {
"a", "b/c/"), "a", "b/c/"),
newTest("a/b/d", newTest("a/b/d",
"a/", "b/c/", "/../d/"), "a/", "b/c/", "/../d/"),
newTest("https://try.gitea.io/a/b/c#d",
"https://try.gitea.io", "a/b", "c#d"),
} { } {
assert.Equal(t, test.Expected, URLJoin(test.Base, test.Elements...)) assert.Equal(t, test.Expected, URLJoin(test.Base, test.Elements...))
} }