generated from axetroy/go-cli-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 8
/
serve.go
83 lines (67 loc) · 1.64 KB
/
serve.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
package watchdog
import (
"embed"
"log"
"net/http"
"strings"
"time"
"github.com/axetroy/watchdog/internal/socket"
)
// skipcq: SCC-compile
//go:embed web/dist
var content embed.FS
var fs = http.FileServer(http.FS(content))
type HTTPHandler struct {
config *Config
}
type ServiceStatus struct {
Name string `json:"name"` // 服务名称
Error string `json:"error"` // 错误信息
UpdatedAt string `json:"updated_at"` // 检测时间
Duration time.Duration `json:"duration"` // 持续时间
}
func (t HTTPHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.URL.Path, "/api/ws") {
s, err := socket.NewSocket(res, req)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
_, _ = res.Write([]byte(err.Error()))
return
}
initPayload := map[string][]ServiceStatus{}
for _, sr := range t.config.Service {
cached := Store.GetItem(sr.Name)
if cached == nil {
initPayload[sr.Name] = []ServiceStatus{}
} else {
initPayload[sr.Name] = *cached
}
}
socket.Pool.BroadcastTo(s.UUID, socket.Data{
Event: socket.EventInit,
Payload: initPayload,
})
defer s.Close()
for {
_, _, err := s.ReadMessage()
if err != nil {
break
}
}
} else {
req.URL.Path = "/web/dist" + req.URL.Path
fs.ServeHTTP(res, req)
}
}
func Serve(port string, config *Config) {
server := http.Server{
Addr: ":" + port,
Handler: &HTTPHandler{
config: config,
},
ReadTimeout: 30 * time.Second,
ReadHeaderTimeout: 30 * time.Second,
}
log.Printf("Listen on %s \n", server.Addr)
log.Fatal(server.ListenAndServe())
}