go - 在 Go 语言服务器中流式传输视频

标签 go video-streaming html5-video

我编写了这个简单的 http 服务器来提供视频文件:

package main

import (
    "net/http"
    "os"
    "bytes"
    "io"
    "fmt"
)

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

rangeValue := r.Header.Get("range")
fmt.Println("Range:")
fmt.Println(rangeValue)

buf := bytes.NewBuffer(nil)
f, _ := os.Open("oceans_1.webm")
io.Copy(buf, f)           // Error handling elided for brevity.
f.Close()

w.Header().Set("Accept-Ranges","bytes")
w.Header().Set("Content-Type", "video/webm")
w.Header().Set("Content-Length","22074728")
w.Header().Set("Last-Modified", "Wed, 29 Nov 2017 17:10:44 GMT")

w.WriteHeader(206)
w.Write(buf.Bytes())
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

视频播放完美,但我无法更改视频时间。当我点击时间线视频光标时,它不会改变位置,视频也不会跳转到特定时间。

当我使用 http.ServeFile(w, r, "oceans_1.webm") 提供视频时,一切正常 - 我可以更改视频时间。

最佳答案

这种不同的行为在 net/http 包中直接解决,在 ServeContent 的文档中(强调我的):

ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

如果检查 net/http 代码,您会看到 ServeFile电话 serveContent (通过 serveFile ),这是由 ServeContent 调用的同一个未导出函数.

我没有深入研究不同行为的原因,但是包上的文档非常清楚为什么您的 io.Copy 策略不起作用,而 http.ServeFile 确实如此。

关于go - 在 Go 语言服务器中流式传输视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47560370/

相关文章:

Django和HTML无法从指定时间开始视频

go - 向代理发送 TCP 数据包

android - 如何在 JavaCV 0.3 Stream Test Android 项目中使用 ffplay 显示视频流?

javascript - Cordova 外部应用 + 本地视频

c++ - 使用 Opencv/c++ 在 Stream 中的两点之间画一条线

ffmpeg - 记录传入的 mjpeg 流?

html - 使用 HTML5 视频跟踪 move/调整大小事件?

go - 如何存储一片 byte slice ?

go - 当 WaitGroup 中的一个 goroutine 发生第一个错误时如何退出?

methods - Go嵌入结构调用子方法而不是父方法