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

Fix HTTP error handling to return proper error #394

Merged
merged 1 commit into from
Aug 28, 2023
Merged
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
23 changes: 20 additions & 3 deletions util/filesystem/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ func (e ErrExeNotFound) Error() string {
return fmt.Sprintf("cannot find %q in your path:\n%q", e.ExeName, e.Path)
}

type ErrHTTP struct {
URL *url.URL
StatusCode int
}

func (e ErrHTTP) Error() string {
return fmt.Sprintf("server returned status code %d fetching %q", e.StatusCode, e.URL.String())
}

// DirExists returns true if the given path exists and is a directory.
func DirExists(path string) bool {
stat, err := os.Stat(path)
Expand All @@ -55,19 +64,27 @@ func CreateDir(path string) (err error) {

// DownloadFile downloads a file from a URL.
func DownloadFile(url *url.URL, filePath string) (err error) {
resp, err := http.Get(url.String())
response, err := http.Get(url.String())
if err != nil {
return
}
defer resp.Body.Close()
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
err = ErrHTTP{
URL: url,
StatusCode: response.StatusCode,
}
return
}

out, err := os.Create(filePath)
if err != nil {
return
}
defer out.Close()

_, err = io.Copy(out, resp.Body)
_, err = io.Copy(out, response.Body)

return
}
Expand Down