-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.go
53 lines (49 loc) · 1.31 KB
/
application.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
package main
import (
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
)
func main() {
http.HandleFunc("/playing/", playing)
if err := http.ListenAndServe(":80", nil); err != nil {
log.Fatalln(err)
}
}
func playing(resp http.ResponseWriter, req *http.Request) {
if file, err := os.Open("d:\\test.mp4"); err != nil {
resp.WriteHeader(500)
return
} else {
defer file.Close()
if stat, err := file.Stat(); err != nil {
resp.WriteHeader(500)
return
} else {
var minRange = "0"
var maxRange = strconv.Itoa(int(stat.Size() - 1))
if req.Header.Get("Range") != "" && strings.Contains(req.Header.Get("Range"), "-") {
r := strings.Split(strings.ReplaceAll(req.Header.Get("Range"), "bytes=", ""), "-")
minRange = r[0]
if len(r) == 2 && r[1] != "" {
maxRange = r[1]
}
resp.Header().Add("Content-Range", strings.Join([]string{"bytes ", r[0], "-", maxRange, "/", strconv.Itoa(int(stat.Size()))}, ""))
}
resp.Header().Add("Content-Length", strconv.Itoa(int(stat.Size())))
resp.Header().Add("Content-Type", "video/mp4")
resp.WriteHeader(206)
seek, _ := strconv.ParseInt(minRange, 10, 64)
file.Seek(seek, io.SeekStart)
buffer := make([]byte, 204800)
for {
if read, err := file.Read(buffer); read != 0 && err != io.EOF {
resp.Write(buffer)
}
}
}
}
}