Created
August 30, 2024 10:43
-
-
Save abhishekkr/50ff341b117a7248ba86f228c71f22b6 to your computer and use it in GitHub Desktop.
A Go program to serve HTML page & Video.. so can open in Chrome and Cast via Tab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
## way to run.. then open http://localhost:8888 in Chrome & Cast your Tab | |
export SERVE_VIDEO_FILE="/path/to/video.mp4" ; \ | |
export SERVE_HTTP_PORT=":8888" ; \ | |
go run serve.go | |
*/ | |
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
) | |
var ( | |
ListenAt = os.Getenv("SERVE_HTTP_PORT") | |
VidFile = os.Getenv("SERVE_VIDEO_FILE") | |
indexHtml = ` | |
<html> | |
<head> | |
<style> | |
body { | |
width: 95%; | |
height: 95vh; | |
display: flex; | |
self-align: center; | |
text-align: center; | |
justify-align: center; | |
} | |
#video-player { | |
width: 100%; | |
height: 100%; | |
margin: 0 auto; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="container"> | |
<video id="video-player" controls controlsList="nodownload" preload="metadata" crossorigin="anonymous"> | |
<source id="video-player-src" src="/video/stream" type="video/mp4"> | |
</video> | |
</div> | |
</body> | |
<script> | |
var container = document.querySelector("#container"); | |
document.onkeydown = function(event) { | |
switch (event.keyCode) { | |
case 37: | |
event.preventDefault(); | |
vid_currentTime = container.currentTime; | |
container.currentTime = vid_currentTime - 5; | |
break; | |
case 39: | |
event.preventDefault(); | |
vid_currentTime = container.currentTime; | |
container.currentTime = vid_currentTime + 5; | |
break; | |
} | |
}; | |
</script> | |
</html> | |
` | |
) | |
func ServeStrAsHtml(s string) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
w.Header().Add("Content-Type", "text/html; charset=utf-8") | |
fmt.Fprintf(w, s) | |
}) | |
} | |
func ServeVideo(vidFile string) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
video, err := os.Open(vidFile) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer video.Close() | |
http.ServeContent(w, r, vidFile, time.Now(), video) | |
}) | |
} | |
func main() { | |
mux := http.NewServeMux() | |
mux.Handle("/video/stream", ServeVideo(VidFile)) | |
mux.Handle("/", ServeStrAsHtml(indexHtml)) | |
log.Println("listening at", ListenAt) | |
log.Fatal(http.ListenAndServe(ListenAt, mux)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment