I have generated the m3u8 file (index.m3u8) from a video and I want to play it on HTML. Basically, I have a golang server which will send the index.m3u8 to the video tag in html5 to play it when http://127.0.0.1:8200/play is called.
my golang file :
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()
}
this is my html file:
<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>
the error i get in console when i go to the url (http://127.0.0.1:8200/play) is
videosource/index.m3u8:1 Failed to load resource: the server responded with a status of 404 (Not Found)
To check that the error is not caused by path error, I tried to replace the '{{.}}'
in HTML with the full path ('videosource/index.m3u8') and it works perfectly.
Please guide me and show me what's wrong with my code.
Thank you.
You have to set your header to the right type. Try something like this:
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")
}