30 lines
637 B
Go
Executable File
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
|
|
}
|