From 674a5b2579ce07a93e5b85649df0f16b9c3893bc Mon Sep 17 00:00:00 2001 From: lixiangwuxian Date: Sun, 20 Oct 2024 01:25:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E5=9B=BE=E7=89=87=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/url.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/util/url.go b/util/url.go index 6dbb0b6..91e5511 100644 --- a/util/url.go +++ b/util/url.go @@ -1,7 +1,11 @@ package util import ( + "fmt" + "io" + "net/http" "net/url" + "os" "strings" ) @@ -31,3 +35,32 @@ func normalizeURL(rawURL string) string { return u.String() } + +func DownloadFile(url string, filepath string) error { + // 发送 HTTP GET 请求 + resp, err := http.Get(url) + if err != nil { + return fmt.Errorf("下载失败: %v", err) + } + defer resp.Body.Close() + + // 检查 HTTP 响应状态码 + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("请求失败,状态码: %d", resp.StatusCode) + } + + // 创建文件 + out, err := os.Create(filepath) + if err != nil { + return fmt.Errorf("创建文件失败: %v", err) + } + defer out.Close() + + // 将响应的内容复制到文件 + _, err = io.Copy(out, resp.Body) + if err != nil { + return fmt.Errorf("保存失败: %v", err) + } + + return nil +}