Ensure upload base path ends in /v1

Signed-off-by: Dan Luhring <dan.luhring@anchore.com>
This commit is contained in:
Dan Luhring 2021-02-01 16:59:23 -05:00
parent 5b5fa7ec90
commit b207bc8ee2
No known key found for this signature in database
GPG key ID: 9CEE23D079426CEF
2 changed files with 49 additions and 0 deletions

View file

@ -31,6 +31,9 @@ func NewClient(cfg Configuration) (*Client, error) {
basePath := ensureURLHasScheme(cfg.BasePath) // we can rely on the built-in URL parsing for the scheme, host,
// port, and path prefix, as long as a scheme is present
basePath = strings.TrimSuffix(basePath, "/")
basePath = ensureURLHasSuffix(basePath,
"/v1") // We need some mechanism to ensure Syft doesn't try to communicate with the wrong API version.
return &Client{
config: cfg,
@ -70,3 +73,11 @@ func ensureURLHasScheme(url string) string {
return url
}
func ensureURLHasSuffix(url, suffix string) string {
if !strings.HasSuffix(url, suffix) {
return url + suffix
}
return url
}

View file

@ -69,3 +69,41 @@ func TestEnsureURLHasScheme(t *testing.T) {
})
}
}
func TestEnsureURLHasSuffix(t *testing.T) {
cases := []struct {
url string
suffix string
expected string
}{
{
url: "http://localhost",
suffix: "/v1",
expected: "http://localhost/v1",
},
{
url: "http://localhost/v1",
suffix: "/v1",
expected: "http://localhost/v1",
},
{
url: "http://localhost/v1/",
suffix: "/v1",
expected: "http://localhost/v1//v1",
},
{
url: "http://localhost-v1",
suffix: "/v1",
expected: "http://localhost-v1/v1",
},
}
for _, testCase := range cases {
t.Run(testCase.url, func(t *testing.T) {
result := ensureURLHasSuffix(testCase.url, testCase.suffix)
if testCase.expected != result {
t.Errorf("expected '%s' but got '%s'", testCase.expected, result)
}
})
}
}