Live-reload middleware for your server. Meant to be drop-n-go, so it's fairly opinionated. Built on top of the lower-level sse package.
- Minimal API for serving, watching and live reloading.
- Customize how livereload behaves a custom event listener.
- Detects the content type and ignores non-HTML files.
- Robust file watching built on top of
fsnotify
.
go get github.com/matthewmueller/livereload
func main() {
ctx := context.Background()
fsys := http.FileServer(http.Dir("example/public"))
fmt.Println("Server started at http://localhost:3000")
lr := livereload.New(slog.Default())
go lr.Watch(ctx, ".")
http.ListenAndServe(":3000", lr.Middleware(fsys))
}
By default, any HTML or text document will be reloaded upon change. If you'd like to better control this behavior, you can implement your own livereload
event handler:
<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<h1>Hello</h1>
</body>
<script>
window.addEventListener("livereload", (e) => {
// Prevent the default livereload handler from running
e.stopImmediatePropagation()
// Listen all the events the watcher discovered
const events = e.detail.events || []
for (let event of events) {
console.log(event.op, event.path)
}
})
</script>
</html>
- Matt Mueller (@mattmueller)
MIT