From f1db13387b45023dcaa7a6d137db18caf14cffad Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:48:00 +0300 Subject: [PATCH] fix(package): [netutil] reject failed download responses (#388) --- netutil/download_status_test.go | 40 +++++++++++++++++++++++++++++++++ netutil/net.go | 3 +++ 2 files changed, 43 insertions(+) create mode 100644 netutil/download_status_test.go diff --git a/netutil/download_status_test.go b/netutil/download_status_test.go new file mode 100644 index 0000000..fa56f77 --- /dev/null +++ b/netutil/download_status_test.go @@ -0,0 +1,40 @@ +package netutil + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +func TestDownloadFileStatus(t *testing.T) { + for _, status := range []int{http.StatusOK, http.StatusNotFound, http.StatusInternalServerError} { + t.Run(http.StatusText(status), func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + w.Write([]byte("response")) + })) + defer server.Close() + path := filepath.Join(t.TempDir(), "download.txt") + if err := os.WriteFile(path, []byte("original"), 0600); err != nil { + t.Fatal(err) + } + err := DownloadFile(path, server.URL) + if (err != nil) != (status != http.StatusOK) { + t.Errorf("unexpected result: %v", err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + want := "original" + if status == http.StatusOK { + want = "response" + } + if string(data) != want { + t.Errorf("got %q, want %q", data, want) + } + }) + } +} diff --git a/netutil/net.go b/netutil/net.go index 93c2277..2300641 100644 --- a/netutil/net.go +++ b/netutil/net.go @@ -288,6 +288,9 @@ func DownloadFile(filepath string, url string) error { return err } defer resp.Body.Close() + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + return fmt.Errorf("download failed: %s", resp.Status) + } out, err := os.Create(filepath) if err != nil {