Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[cpackget] Retry download without User-Agent header #413

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions cmd/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,16 @@ func DownloadFile(URL string, timeout int) (string, error) {
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusNotFound {
// resend GET request without user agent header
req.Header.Del("User-Agent")
resp, err = client.Do(req)
if err != nil {
log.Error(err)
return "", fmt.Errorf("\"%s\": %w", URL, errs.ErrFailedDownloadingFile)
}
}

if resp.StatusCode == http.StatusForbidden {
cookie := resp.Header.Get("Set-Cookie")
if len(cookie) > 0 {
Expand Down
26 changes: 26 additions & 0 deletions cmd/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,32 @@ func TestDownloadFile(t *testing.T) {
assert.Equal(bytes, goodResponse)
})

t.Run("test download user agent not allowed", func(t *testing.T) {
fileName := "file.txt"
defer os.Remove(fileName)
utils.SetUserAgent("cpackget")
goodResponse := []byte("all good")
goodServer := httptest.NewServer(
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
userAgent := r.Header.Get("User-Agent")
if len(userAgent) > 0 && strings.Contains(userAgent, "cpackget") {
w.WriteHeader(http.StatusNotFound)
} else {
fmt.Fprint(w, string(goodResponse))
}
},
),
)
url := goodServer.URL + "/" + fileName
_, err1 := utils.DownloadFile(url, 0)
assert.Nil(err1)
assert.True(utils.FileExists(fileName))
bytes, err2 := os.ReadFile(fileName)
assert.Nil(err2)
assert.Equal(bytes, goodResponse)
})

t.Run("test download set cookie", func(t *testing.T) {
fileName := "file.txt"
defer os.Remove(fileName)
Expand Down
Loading