feat: 添加下载图片功能

This commit is contained in:
lixiangwuxian 2024-10-20 01:25:49 +08:00
parent d26007d563
commit 674a5b2579

View File

@ -1,7 +1,11 @@
package util package util
import ( import (
"fmt"
"io"
"net/http"
"net/url" "net/url"
"os"
"strings" "strings"
) )
@ -31,3 +35,32 @@ func normalizeURL(rawURL string) string {
return u.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
}