Files
x/net/http/download.go
Colin Henry 54aae5f242
All checks were successful
Go / build (1.23) (push) Successful in 3m51s
big updates: tests, bug fixed, documentation. oh my
2026-01-03 15:53:50 -08:00

30 lines
637 B
Go
Executable File

package http
import (
"fmt"
std "net/http"
osx "git.sdf.org/jchenry/x/os"
)
// DownloadFile downloads a file from the given URL and saves it to the specified path.
// Returns an error if the HTTP request fails, the response status is not 200 OK, or file writing fails.
func DownloadFile(url, path string) error {
resp, err := std.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != std.StatusOK {
return fmt.Errorf("download failed: unexpected status code %d: %s", resp.StatusCode, resp.Status)
}
err = osx.CopyToNewFile(path, resp.Body)
if err != nil {
return err
}
return nil
}