-
Notifications
You must be signed in to change notification settings - Fork 0
/
goreload.go
46 lines (38 loc) · 1.1 KB
/
goreload.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
package goreload
import (
"context"
"fmt"
"io"
"github.com/a-h/templ"
"github.com/idreaminteractive/goreload/internal/commands"
"github.com/idreaminteractive/goreload/internal/hotreload"
)
// Programmatically trigger the hot reload for the server running @ reloadServerUrl
func SendReloadSignal(reloadServerUrl string) error {
return commands.SignalReload(reloadServerUrl)
}
// Embed the JS to connect to the hot reload server and wait for SSE events @ reloadServerUrl
func ReloadComponent(reloadServerUrl string) templ.Component {
host, _, err := hotreload.ValidateUrl(reloadServerUrl)
if err != nil {
panic(err)
}
url := host + "/hotreload"
output := fmt.Sprintf(`
<script type="text/javascript">
(function () {
let reloadSrc = window.goreload_reloadSrc || new EventSource("%s");
reloadSrc.onmessage = (event) => {
if (event && event.data === "reload") {
window.location.reload();
}
};
window.reloadSrc = reloadSrc;
})();
</script>
`, url)
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
_, err := io.WriteString(w, output)
return err
})
}