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
package main

import (
"log"
"net/http"
"os"
"time"
)

func video(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "video/mp4")
file, err := os.Open("/Users/sherlockgy/Downloads/1.mp4")
if err != nil {
log.Println("文件打开异常...")
return
}
http.ServeContent(response, request, "test", time.Now(), file)
defer file.Close()
}

func main() {
http.HandleFunc("/video", video) // 设置访问的路由
err := http.ListenAndServe(":9090", nil) // 设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}