golang 视频文件下载
程序员文章站
2022-05-29 22:25:22
...
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 文件url需要修改成目标地址
fileUrl := "http://asdlkskldko90/adk/asdlks/kajsd=?lksadklko&jmasdn1928="
err := DownloadFile("22.mp4", fileUrl)
if err != nil {
panic(err)
}
fmt.Println("Downloaded: " + fileUrl)
}
// DownloadFile will download a url to a local file. It's efficient because it will
// write as it downloads and not load the whole file into memory.
func DownloadFile(filepath string, url string) error {
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
return err
}
执行:
go run main.go
查看下载文件:
[email protected]:/tmp/zz# ll
total 1972
-rw-r--r-- 1 root root 3949617 Feb 4 11:06 22.mp4
-rw-r--r-- 1 root root 1341 Feb 4 11:00 main.go
[email protected]:/tmp/zz#
上一篇: CentOS7.6中 KVM虚拟机内存、CPU调整
下一篇: 你TM瞎哭什么啊,那是我妈