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

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

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

我有一个包含网站 url 输入的页面(例如 youtube url),我想在我的服务器中使用 Golang 调用带有此 url 的 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}

我可以下载一个文件,但它没有按预期工作。我什至无法打开文件。

最佳答案

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

关于go - Youtube-dl直接下载到客户端浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56805314/

相关文章:

testing - 在 goroutine 中使用 Gock 和 HTTP 调用时的数据竞争

golang 检查是否启用了 javascript

javascript - 移动浏览器中的 DOM2 事件?

c++ - 将托管 C# DLL 包含到非托管 C++ DLL 中——全部在一个文件中

go - 素数程序给出了错误的答案

go - Prometheus Go 客户端库的 ExponentialBuckets API 的最低粒度是多少?

javascript - 从 Windows 服务 C# 调用 javascript 函数

javascript - jquery 可以操作用 DOM 创建的临时文档吗?

c# - 实现命令行解释器

linux - Bash 权限被拒绝