livereload is a small Go helper for development-time live reloading. It exposes a WebSocket endpoint and provides a browser snippet that reconnects after a server restart and refreshes the page automatically.
go get github.com/kodehat/livereload- Go 1.26+
- A
net/httpserver
Register the WebSocket endpoint:
Only register the route and inject the script when your app is running in a development mode.
package main
import (
"fmt"
"net/http"
"time"
"github.com/kodehat/livereload"
)
func main() {
mux := http.NewServeMux()
params := livereload.NewParams()
mux.HandleFunc(params.ReloadPath, livereload.Handler(params))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(`
<!doctype html>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Hello</h1>
` + string(livereload.Script(params)) + `
</body>
</html>`))
})
http.ListenAndServe(":8080", mux)
}If your app is mounted under a sub-path, build params with options:
params := livereload.NewParams(
livereload.WithContextPath("/myapp"),
livereload.WithReloadPath("/events"),
livereload.WithPingInterval(5*time.Second),
livereload.WithMaxReconnects(10),
livereload.WithReconnectDelay(2*time.Second),
)
fmt.Fprint(w, livereload.Script(params))Params stores the app ContextPath, websocket ReloadPath, and reconnect timing.
Creates a Params value with these defaults:
ContextPath:""(root-mounted app)ReloadPath:"/reload"PingInterval:2sMaxReconnects:5ReconnectDelay:1s
Use WithContextPath, WithReloadPath, WithPingInterval, WithMaxReconnects, and WithReconnectDelay to override specific values.
Functional option used by NewParams.
Helpers for customizing Params when constructing it with NewParams.
Returns a handler for the websocket endpoint. params.PingInterval controls how often the connection is pinged.
Returns the JavaScript snippet to inject into HTML pages. params.ContextPath is the app base path, params.ReloadPath overrides the websocket endpoint path, and params.MaxReconnects plus params.ReconnectDelay control the reconnect loop.
- The browser opens a WebSocket connection to
contextPath + reloadPath. - While the server is running, the connection stays alive.
- When the server restarts, the socket closes.
- The script retries the connection.
- Once the connection is restored, the page reloads automatically.
- The snippet is intended for development use.
- Keep both the route and the script out of production builds.
- Inject it into your HTML before
</body>or in<head>.