-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
108 lines (92 loc) · 2.41 KB
/
server.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
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os/exec"
"runtime"
"time"
)
func serveHTML(ctx context.Context, pr ParseResult) {
loaded := make(chan struct{})
charts := generateCharts(pr)
http.HandleFunc("GET /", func(writer http.ResponseWriter, request *http.Request) {
rendered, err := render(pr, charts, true)
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
_, _ = writer.Write([]byte(fmt.Sprintf("Error rendering HTML: %s", err)))
slog.Error("Error rendering HTML", "err", err)
return
}
_, _ = writer.Write([]byte(rendered))
})
http.HandleFunc("GET /loaded", func(writer http.ResponseWriter, request *http.Request) {
loadedHandler(writer, request, loaded)
})
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
slog.Error("Error creating listener", "err", err)
return
}
port := listener.Addr().(*net.TCPAddr).Port
ctx, cancel := context.WithCancel(ctx)
defer cancel()
server := &http.Server{}
go func() {
err := server.Serve(listener)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("Error serving", "err", err)
}
}()
url := fmt.Sprintf("http://localhost:%d", port)
slog.Debug("Opening %s in your browser", "url", url)
err = openBrowser(url)
if err != nil {
slog.Error("Error opening browser", "err", err)
return
}
if !keepRunning {
select {
case <-loaded:
slog.Debug("Browser successfully loaded the page.")
case <-time.After(10 * time.Second):
slog.Error("Timeout: Browser did not load the page within 10 seconds.")
case <-ctx.Done():
slog.Debug("Context was canceled.")
}
} else {
select {
case <-ctx.Done():
slog.Debug("Context was canceled.")
}
}
slog.Debug("Shutting down the server...")
if err := server.Shutdown(ctx); err != nil {
slog.Error("Error shutting down server", "err", err)
}
}
func loadedHandler(w http.ResponseWriter, r *http.Request, loaded chan struct{}) {
// Signal that the page has been loaded
select {
case loaded <- struct{}{}:
default:
// Channel already signaled, do nothing
}
}
func openBrowser(url string) error {
var cmd *exec.Cmd
switch runtime.GOOS {
case "linux":
cmd = exec.Command("xdg-open", url)
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
case "darwin":
cmd = exec.Command("open", url)
default:
return fmt.Errorf("unsupported platform")
}
return cmd.Start()
}