forked from aerokube/selenoid-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (98 loc) · 2.31 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
106
107
108
109
110
package main
import (
"context"
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
//go:generate go-bindata-assetfs data/
var (
listen string
selenoidUri string
period time.Duration
)
func httpDo(ctx context.Context, req *http.Request, handle func(*http.Response, error) error) error {
// Run the HTTP request in a goroutine and pass the response to handle function
errChan := make(chan error, 1)
go func() {
errChan <- handle(http.DefaultClient.Do(req))
}()
select {
case <-ctx.Done():
{
<-errChan // Wait for handle to return.
return ctx.Err()
}
case err := <-errChan:
{
return err
}
}
}
func Status(ctx context.Context, baseUrl string) ([]byte, error) {
req, err := http.NewRequest("GET", baseUrl+"/status", nil)
if err != nil {
return nil, err
}
timedCtx, _ := context.WithTimeout(ctx, 1 * time.Second)
var results []byte
err = httpDo(ctx, req.WithContext(timedCtx), func(resp *http.Response, err error) error {
if err != nil {
return err
}
defer resp.Body.Close()
results, err = ioutil.ReadAll(resp.Body)
return err
})
return results, err
}
func mux(sse *SseBroker) http.Handler {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(assetFS()))
mux.Handle("/events", sse)
return mux
}
func init() {
flag.StringVar(&listen, "listen", ":8080", "host and port to listen on")
flag.StringVar(&selenoidUri, "selenoid-uri", "http://localhost:4444", "selenoid uri to fetch data from")
flag.DurationVar(&period, "period", 5*time.Second, "data refresh period, e.g. 5s or 1m")
flag.Parse()
}
func main() {
broker := NewSseBroker()
stop := make(chan os.Signal)
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
go func() {
ticker := time.NewTicker(period)
for {
ctx, cancel := context.WithCancel(context.Background())
select {
case <-ticker.C:
{
if (broker.HasClients()) {
res, err := Status(ctx, selenoidUri)
if err != nil {
log.Printf("can't get status (%s)\n", err)
broker.Notifier <- []byte(`{ "errors": [{"msg": "can't get status"}] }`)
continue
}
broker.Notifier <- res
}
}
case <-stop:
{
cancel()
ticker.Stop()
os.Exit(0)
}
}
}
}()
log.Printf("Listening on %s\n", listen)
log.Fatal(http.ListenAndServe(listen, mux(broker)))
}