欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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#