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

Youtube-dl download to client browser directly

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

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

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

我在网上和这里尝试了很多东西。您可以在下面找到我的代码片段。

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}

我可以下载文件,但没有按预期运行。我什至无法打开文件。

只需将 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())
    }
}