html video 标签在 golang 服务器提供服务时不播放 m3u8 文件

html video tag not playing m3u8 file when serve by golang server

我已经从视频生成了 m3u8 文件 (index.m3u8),我想在 HTML 上播放它。 基本上,我有一个 golang 服务器,它会将 index.m3u8 发送到 html5 中的视频标签,以便在调用 http://127.0.0.1:8200/play 时播放它。

我的 golang 文件:

package main

import(
"fmt"
"net/http"
"html/template"
)


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

    tmpl := template.Must(template.ParseFiles("index.html"))

    tmpl.Execute(w, "videosource/index.m3u8")

}


func main(){

fmt.Println("begin listening to port 8200")

server := http.Server{
    Addr: "127.0.0.1:8200",
}
http.HandleFunc("/play",serveHandler)
server.ListenAndServe()

}

这是我的 html 文件:

<html>
  <body>
<script src="https://cdn.jsdelivr.net/npm/hls.js@canary"></script>
<video id="video" controls autoplay></video>
<script>
if(Hls.isSupported())
{
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('{{.}}');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function()
    {
        video.play();
    });
}
else if (video.canPlayType('application/vnd.apple.mpegurl'))
{
    video.src = '{{.}}';
    video.addEventListener('canplay',function()
    {
        video.play();
    });
}
</script>

当我转到 url (http://127.0.0.1:8200/play) 时,控制台出现的错误是

videosource/index.m3u8:1 Failed to load resource: the server responded with a status of 404 (Not Found)

为了检查错误不是由路径错误引起的,我尝试将 HTML 中的 '{{.}}' 替换为完整路径 ('videosource/index.m3u8'),并且效果很好。

请指导我并告诉我我的代码有什么问题。

谢谢。

您必须将 header 设置为正确的类型。 尝试这样的事情:

func serveHandler(w http.ResponseWriter, r *http.Request){
  w.Header().Set("Content-Type", "application/x-mpegURL")

  tmpl := template.Must(template.ParseFiles("index.html"))
  tmpl.Execute(w, "videosource/index.m3u8")

}