file serving implemented, video served with hls.js

This commit is contained in:
Muaz Ahmad 2023-08-21 15:11:19 +05:00
parent 14336095ea
commit 880d010989
2 changed files with 29 additions and 5 deletions

View file

@ -4,6 +4,7 @@ import (
"net/http" "net/http"
"strings" "strings"
"os" "os"
"html/template"
) )
func NewServer(port string) (error) { func NewServer(port string) (error) {
@ -16,12 +17,22 @@ func NewServer(port string) (error) {
} }
func server_setup(server *http.ServeMux) { func server_setup(server *http.ServeMux) {
server.HandleFunc("/", serve_main_page) server.HandleFunc("/live/", serve_main_page)
server.HandleFunc("/live/", serve_live_playlist) server.HandleFunc("/list/", serve_live_playlist)
server.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
server.HandleFunc("/vid/", serve_vid_segment)
}
func serve_vid_segment(w http.ResponseWriter, r *http.Request) {
base_dir, _ := os.UserHomeDir()
tmp := strings.Split(strings.TrimPrefix(r.URL.Path, "/vid/"), "/")
stream_key := tmp[0]
segment_file := tmp[1]
http.ServeFile(w, r, base_dir + "/live/" + stream_key + "/" + segment_file)
} }
func serve_live_playlist(w http.ResponseWriter, r *http.Request) { func serve_live_playlist(w http.ResponseWriter, r *http.Request) {
stream_id := strings.TrimPrefix(r.URL.Path, "/live/") stream_id := strings.TrimPrefix(r.URL.Path, "/list/")
base_dir, _ := os.UserHomeDir() base_dir, _ := os.UserHomeDir()
stream_playlist_path := base_dir + "/live/" + stream_id + "/stream.m3u8" stream_playlist_path := base_dir + "/live/" + stream_id + "/stream.m3u8"
if _, err := os.Stat(stream_playlist_path); err != nil { if _, err := os.Stat(stream_playlist_path); err != nil {
@ -32,5 +43,8 @@ func serve_live_playlist(w http.ResponseWriter, r *http.Request) {
} }
func serve_main_page(w http.ResponseWriter, r *http.Request) { func serve_main_page(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/index.html") w.Header().Set("Access-Control-Allow-Origin", "*")
page := template.Must(template.ParseFiles("static/index.html"))
stream_user := strings.TrimPrefix(r.URL.Path, "/live/")
page.Execute(w, stream_user)
} }

View file

@ -4,6 +4,16 @@
<title>Test</title> <title>Test</title>
</head> </head>
<body> <body>
<h1>Test</h1> <video id=vid1 autoplay muted></video>
</body> </body>
<script src="https://cdn.jsdelivr.net/npm/hls.js@1"></script>
<script>
var video = document.getElementById("vid1");
var videoSrc = "/list/{{.}}";
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(videoSrc);
hls.attachMedia(video);
}
</script>
</html> </html>