-
Notifications
You must be signed in to change notification settings - Fork 98
/
main.go
executable file
·105 lines (89 loc) · 1.99 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"context"
"embed"
"html/template"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gin-gonic/gin"
"github.com/wujunwei928/parse-video/parser"
)
type HttpResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
//go:embed templates/*
var files embed.FS
func main() {
r := gin.Default()
sub, err := fs.Sub(files, "templates")
if err != nil {
panic(err)
}
tmpl := template.Must(template.ParseFS(sub, "*.tmpl"))
r.SetHTMLTemplate(tmpl)
r.GET("/", func(c *gin.Context) {
c.HTML(200, "index.tmpl", gin.H{
"title": "github.com/wujunwei928/parse-video Demo",
})
})
r.GET("/video/share/url/parse", func(c *gin.Context) {
paramUrl := c.Query("url")
parseRes, err := parser.ParseVideoShareUrlByRegexp(paramUrl)
jsonRes := HttpResponse{
Code: 200,
Msg: "解析成功",
Data: parseRes,
}
if err != nil {
jsonRes = HttpResponse{
Code: 201,
Msg: err.Error(),
}
}
c.JSON(http.StatusOK, jsonRes)
})
r.GET("/video/id/parse", func(c *gin.Context) {
videoId := c.Query("video_id")
source := c.Query("source")
parseRes, err := parser.ParseVideoId(source, videoId)
jsonRes := HttpResponse{
Code: 200,
Msg: "解析成功",
Data: parseRes,
}
if err != nil {
jsonRes = HttpResponse{
Code: 201,
Msg: err.Error(),
}
}
c.JSON(200, jsonRes)
})
srv := &http.Server{
Addr: ":8080",
Handler: r,
}
go func() {
// 服务连接
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// 等待中断信号以优雅地关闭服务器 (设置 5 秒的超时时间)
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}