/
backend_static_file_system.go
102 lines (85 loc) · 2.33 KB
/
backend_static_file_system.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
package base
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/ChineseSubFinder/ChineseSubFinder/pkg/settings"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
type StaticFileSystemBackEnd struct {
logger *logrus.Logger
running bool
srv *http.Server
locker sync.Mutex
pathUrlMap map[string]string
}
func NewStaticFileSystemBackEnd(logger *logrus.Logger) *StaticFileSystemBackEnd {
return &StaticFileSystemBackEnd{
logger: logger,
pathUrlMap: make(map[string]string),
}
}
// GetPathUrlMap x://电影 -- /movie_dir_0 or x://电视剧 -- /series_dir_0
func (s *StaticFileSystemBackEnd) GetPathUrlMap() map[string]string {
return s.pathUrlMap
}
func (s *StaticFileSystemBackEnd) Start(commonSettings *settings.CommonSettings) {
defer s.locker.Unlock()
s.locker.Lock()
if s.running == true {
s.logger.Warningln("StaticFileSystemBackEnd is already running")
return
}
s.running = true
router := gin.Default()
// 添加电影的
for i, path := range commonSettings.MoviePaths {
nowUrl := "/movie_dir_" + fmt.Sprintf("%d", i)
s.pathUrlMap[path] = nowUrl
router.StaticFS(nowUrl, http.Dir(path))
}
// 添加连续剧的
for i, path := range commonSettings.SeriesPaths {
nowUrl := "/series_dir_" + fmt.Sprintf("%d", i)
s.pathUrlMap[path] = nowUrl
router.StaticFS(nowUrl, http.Dir(path))
}
s.srv = &http.Server{
Addr: ":" + commonSettings.LocalStaticFilePort,
Handler: router,
}
go func() {
// service connections
s.logger.Infoln("Listening and serving HTTP on port " + commonSettings.LocalStaticFilePort)
if err := s.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
s.logger.Errorln("StaticFileSystemBackEnd listen:", err)
}
}()
}
func (s *StaticFileSystemBackEnd) Stop() {
defer func() {
s.locker.Unlock()
}()
s.locker.Lock()
if s.running == false {
s.logger.Warningln("StaticFileSystemBackEnd is not running")
return
}
defer func() {
s.pathUrlMap = make(map[string]string)
}()
s.running = false
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.srv.Shutdown(ctx); err != nil {
s.logger.Errorln("Server Shutdown:", err)
}
select {
case <-ctx.Done():
s.logger.Warningln("timeout of 5 seconds.")
}
s.logger.Infoln("Static File System Server exiting")
}