forked from muxinc/chunked-transfer-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
58 lines (51 loc) · 1.5 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
package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"time"
)
const (
maximumChunkSizeBytes = 256000
)
func main() {
http.HandleFunc("/manifest.m3u8", manifestHandler)
http.HandleFunc("/ts/", segmentHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func manifestHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Serving manifest")
dat, err := ioutil.ReadFile("assets/manifest.m3u8")
if err != nil {
log.Fatalf("Error reading manifest file, exiting: %v", err)
}
w.Header().Add("Content-Type", "application/x-mpegURL")
w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Write(dat)
}
func segmentHandler(w http.ResponseWriter, r *http.Request) {
segmentName := r.URL.Path
log.Printf("Received request: %s\n", segmentName)
dat, err := ioutil.ReadFile(fmt.Sprintf("assets%s", segmentName))
if err != nil {
log.Printf("Error reading data file, exiting: %v", err)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Add("Content-Type", "video/MP2T")
w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Add("Access-Control-Allow-Origin", "*")
chunks := int(math.Ceil(float64(len(dat)) / float64(maximumChunkSizeBytes)))
for index := 0; index < chunks; index++ {
begin := index * maximumChunkSizeBytes
end := ((index + 1) * maximumChunkSizeBytes)
if end > len(dat) {
end = len(dat)
}
w.Write(dat[begin:end])
time.Sleep(time.Millisecond * 500)
}
}