golang通过资源连接地址下载资源
可以使用标准库中的net/http包来实现下载资源。
示例代码:
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
url := "https://example.com/resource.zip"
fileName := "resource.zip"
// 创建HTTP客户端
client := &http.Client{}
// 创建HTTP请求
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("创建HTTP请求失败:", err)
return
}
// 发送HTTP请求
resp, err := client.Do(req)
if err != nil {
fmt.Println("发送HTTP请求失败:", err)
return
}
defer resp.Body.Close()
// 创建本地文件
file, err := os.Create(fileName)
if err != nil {
fmt.Println("创建本地文件失败:", err)
return
}
defer file.Close()
// 将HTTP响应的Body写入本地文件
_, err = io.Copy(file, resp.Body)
if err != nil {
fmt.Println("写入本地文件失败:", err)
return
}
fmt.Println("下载完成")
}
在上面的示例代码中,我们首先定义了要下载的资源的URL和本地文件名。然后,我们创建了一个HTTP客户端,并使用NewRequest方法创建了一个GET请求。接着,我们发送HTTP请求,并将响应的Body写入本地文件中。最后,我们打印出下载完成的消息
原文地址: https://www.cveoy.top/t/topic/fipI 著作权归作者所有。请勿转载和采集!