Youtube-dl直接下载到客户端浏览器

时间:2019-06-28 10:31:23

标签: go browser command-line youtube-dl download-manager

我想在Windows中使用youtube-dl exe文件通过Golang Web App将视频下载到客户端的浏览器。

我有一个页面,其中包含网站网址(例如youtube网址)的输入,并且我想在Golang服务器中使用此网址调用youtube.dl exe文件。但是我无法将文件直接下载到客户端的浏览器。

我不想将视频本身下载到我的服务器上。我希望将其直接下载到客户端的浏览器。

我在网上以及在这里尝试过很多事情。您可以在下面找到我的代码段。

func SearchHandler(w http.ResponseWriter, r *http.Request) {

// - --------------------------------------------------------------------------------------------------------------
// - Retrieve the HTML form parameter of POST method
// - --------------------------------------------------------------------------------------------------------------
url := r.FormValue("entry-domain")

logger.Printf("SearchHandler started to research the IP and MX data from %s domain", url)
fmt.Println("starting download................")
cmd := exec.Command("youtube-dl.exe", "-o", "-", url)
fmt.Println("downloading started...............")


out, err := cmd.CombinedOutput()
if err != nil {
    log.Fatalf("cmd.Run() failed with %s\n", err)
}

// //copy the relevant headers. If you want to preserve the downloaded file name, extract it with go's url parser.
w.Header().Set("Content-Disposition", "attachment; filename=BigBuckBunny.mp4")
w.Header().Set("Content-Type", "application/octet-stream")

//stream the body to the client without fully loading it into memory
reader := bytes.NewReader(out)
//w.Write(out)
io.Copy(w, reader)
fmt.Println("written to file.....................")
return}

我可以下载文件,但无法正常工作。我什至无法打开文件。

1 个答案:

答案 0 :(得分:2)

只需将ResponseWriter分配给命令的Stdout字段。我还建议在请求上下文中使用exec.CommandContext,以便在客户端中止请求时迅速终止youtube-dl。

func SearchHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Disposition", "attachment; filename=BigBuckBunny.mp4")
    w.Header().Set("Content-Type", "application/octet-stream") 
    // or more precisely: w.Header().Set("Content-Type", "video/mp4") 

    url := r.FormValue("entry-domain")

    stderr := &bytes.Buffer{}

    cmd := exec.CommandContext(r.Context(), "youtube-dl.exe", "-o", "-", url)
    cmd.Stdout = w
    cmd.Stderr = stderr

    if err := cmd.Run(); err != nil {
        log.Println(err)
        log.Println("stderr:", buf.String())
    }
}
相关问题