golang 视频文件下载
原创
©著作权归作者所有:来自51CTO博客作者冰糖豆豆的原创作品,请联系作者获取转载授权,否则将追究法律责任
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
}
执行:
查看下载文件:
root@ubuntu:/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
root@ubuntu:/tmp/zz#