Documentation
¶
Overview ¶
Package livereload provides a WebSocket-based live-reload handler and a JavaScript snippet for use during development. When the server restarts, the WebSocket connection drops; the browser-side snippet detects the close, reconnects, and calls location.reload() once the server is back up.
Usage:
// Register the WebSocket endpoint params := livereload.NewParams() mux.HandleFunc(params.ReloadPath, livereload.Handler(params)) // Inject the JS snippet into every HTML page (before </body> or in <head>) fmt.Fprint(w, livereload.Script(params))
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Handler ¶
func Handler(params Params) http.HandlerFunc
Handler returns an http.HandlerFunc that upgrades the connection to a WebSocket and keeps it alive with periodic pings. Params.PingInterval controls the ping cadence. When the server shuts down or restarts, the connection is closed with StatusGoingAway, causing the browser-side script to detect the disconnect and trigger a reload.
func Script ¶
Script returns the JavaScript snippet that should be injected into every HTML page during development. It opens a WebSocket to params.ContextPath+ params.ReloadPath, uses Params.MaxReconnects and Params.ReconnectDelay for reconnect behavior, and calls location.reload() when the server comes back after a restart.
The returned value is html/template.HTML so it can be used safely with Go's html/template package without additional escaping.
Types ¶
type Option ¶
type Option func(*Params)
Option configures Params values for NewParams.
func WithContextPath ¶
WithContextPath sets the app mount path.
func WithMaxReconnects ¶
WithMaxReconnects sets the browser reconnect limit.
func WithPingInterval ¶
WithPingInterval sets the websocket ping interval.
func WithReconnectDelay ¶
WithReconnectDelay sets the reconnect delay used by the browser script.
func WithReloadPath ¶
WithReloadPath sets the websocket endpoint path.
type Params ¶
type Params struct {
// ContextPath is the path where the app is mounted.
ContextPath string
// ReloadPath is the websocket endpoint path. Empty uses /reload.
ReloadPath string
// PingInterval controls how often the server pings the websocket. Zero
// uses the default 2s interval.
PingInterval time.Duration
// MaxReconnects limits how many reconnect attempts the browser makes. Zero
// uses the default of 5.
MaxReconnects int
// ReconnectDelay controls the base delay between reconnect attempts. Zero
// uses the default of 1s.
ReconnectDelay time.Duration
}
Params configures the app context path, websocket reload path, and timing settings used by the reconnect loop. Use NewParams to construct a Params value with defaults and functional options.