-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (70 loc) · 2.17 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
)
func main() {
var port = GetPort()
http.Handle("/", handlers())
fmt.Printf("Starting server on %s\n", port)
// serve and log errors
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s", port), nil))
}
func handlers() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", indexPage).Methods("GET")
router.HandleFunc("/media/{mID:[0-9]+}/stream", streamHandler).Methods("GET")
router.HandleFunc("/media/{mID:[0-9]+}/{segName:index[0-9]+.ts}", streamHandler).Methods("GET")
return router
}
func indexPage(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
}
func streamHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
mID, err := strconv.Atoi(vars["mID"])
if err != nil {
response.WriteHeader(http.StatusNotFound)
return
}
segName, ok := vars["segName"]
if !ok {
mediaBase := getMediaBase(mID)
m3u8Name := "index.m3u8"
serveHlsM3u8(response, request, mediaBase, m3u8Name)
} else {
fmt.Println("Requesting Video")
mediaBase := getMediaBase(mID)
serveHlsTs(response, request, mediaBase, segName)
}
}
func getMediaBase(mID int) string {
mediaRoot := "assets/media"
return fmt.Sprintf("%s/%d", mediaRoot, mID)
}
func serveHlsM3u8(w http.ResponseWriter, r *http.Request, mediaBase, m3u8Name string) {
mediaFile := fmt.Sprintf("%s/hls/%s", mediaBase, m3u8Name)
http.ServeFile(w, r, mediaFile)
w.Header().Set("Content-Type", "application/x-mpegURL")
w.Header().Set("Access-Control-Allow-Origin", "*")
}
func serveHlsTs(w http.ResponseWriter, r *http.Request, mediaBase, segName string) {
mediaFile := fmt.Sprintf("%s/hls/%s", mediaBase, segName)
http.ServeFile(w, r, mediaFile)
w.Header().Set("Content-Type", "video/MP2T")
w.Header().Set("Access-Control-Allow-Origin", "*")
}
//GetPort is getting the port from the environment so we can run on Heroku
func GetPort() string {
var port = os.Getenv("PORT")
// Set a default port if there is nothing in the environment
if port == "" {
port = "5000"
fmt.Println("INFO: No PORT environment variable detected, defaulting to " + port)
}
return ":" + port
}