-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtuna.go
58 lines (53 loc) · 1.31 KB
/
tuna.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 (
"bufio"
"fmt"
"io"
"net/http"
"strings"
"time"
log "github.com/tominescu/double-golang/simplelog"
)
func tunaTsHandler(w http.ResponseWriter, r *http.Request) {
log.Info("Request URL:%s", r.URL)
url := "https://iptv.tsinghua.edu.cn" + strings.TrimPrefix(r.URL.Path, "/tuna")
bt := time.Now()
resp, err := http.Get(url)
if err != nil {
http.Error(w, err.Error(), 503)
return
}
defer resp.Body.Close()
n, err := io.Copy(w, resp.Body)
et := time.Now()
cost := et.Sub(bt).Nanoseconds()
log.Info("Curl url: %s download: %.2fMB cost: %.2fs speed:%.2fMbps", url, float64(n)/1024/1024, float64(cost)/1e9, float64(n)/float64(cost)*1e9/1024/1024*8)
}
func tunaHandler(w http.ResponseWriter, r *http.Request) {
log.Info("Request URL:%s", r.URL)
err := r.ParseForm()
if err != nil {
http.Error(w, http.StatusText(503), 503)
return
}
id := r.Form.Get("id")
if id == "" {
http.Error(w, http.StatusText(503), 503)
return
}
url := "https://iptv.tsinghua.edu.cn/hls/" + id + ".m3u8"
resp, err := http.Get(url)
if err != nil {
http.Error(w, err.Error(), 503)
return
}
defer resp.Body.Close()
sc := bufio.NewScanner(resp.Body)
for sc.Scan() {
line := sc.Text()
if strings.HasSuffix(line, ".ts") {
line = "http://" + r.Host + "/tuna/hls/" + line
}
fmt.Fprintln(w, line)
}
}