-
Notifications
You must be signed in to change notification settings - Fork 30
/
web.go
110 lines (89 loc) · 2.1 KB
/
web.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
106
107
108
109
110
// SPDX-FileCopyrightText: 2023 Iván Szkiba
// SPDX-FileCopyrightText: 2023 Raintank, Inc. dba Grafana Labs
//
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-License-Identifier: MIT
package dashboard
import (
"errors"
"io/fs"
"net"
"net/http"
"path"
"time"
"github.com/sirupsen/logrus"
)
const (
pathEvents = "/events"
pathUI = "/ui/"
pathReport = "/report"
eventChannel = "events"
snapshotEvent = "snapshot"
cumulativeEvent = "cumulative"
startEvent = "start"
stopEvent = "stop"
configEvent = "config"
metricEvent = "metric"
paramEvent = "param"
thresholdEvent = "threshold"
)
type webServer struct {
*eventEmitter
*http.ServeMux
server *http.Server
}
func newWebServer(
uiFS fs.FS,
reportHandler http.Handler,
logger logrus.FieldLogger,
) *webServer { //nolint:ireturn
srv := &webServer{
eventEmitter: newEventEmitter(eventChannel, logger),
ServeMux: http.NewServeMux(),
}
srv.Handle(pathEvents, srv.eventEmitter)
srv.Handle(pathUI, http.StripPrefix(pathUI, http.FileServer(http.FS(uiFS))))
srv.Handle(pathReport, reportHandler)
srv.HandleFunc("/", rootHandler(pathUI))
srv.server = &http.Server{
Handler: srv.ServeMux,
ReadHeaderTimeout: time.Second,
} //nolint:exhaustruct
return srv
}
func (srv *webServer) listenAndServe(addr string) (*net.TCPAddr, error) {
listener, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
go func() {
serr := srv.server.Serve(listener)
if serr != nil && !errors.Is(serr, http.ErrServerClosed) {
srv.logger.Error(serr)
}
}()
a, _ := listener.Addr().(*net.TCPAddr)
return a, nil
}
func (srv *webServer) stop() error {
srv.eventEmitter.Close()
err := srv.server.Close()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
func rootHandler(uiPath string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { //nolint:varnamelen
if r.URL.Path == "/" {
http.Redirect(
w,
r,
path.Join(uiPath, r.URL.Path)+"?endpoint=/",
http.StatusTemporaryRedirect,
)
return
}
http.NotFound(w, r)
}
}