fix(package): [netutil] reject failed download responses (#388)

This commit is contained in:
Yusuf Efe authored and GitHub committed 2026-10-22 10:48:00 +08:00
1 parent be9b167a9b
commit f1db13387b
2 files changed
+43

No files matched your search

+40
View File
@@ -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)
}
})
}
}
+3
View File
@@ -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 {