Documentation
¶
Overview ¶
Package dev wires hot reload onto a render-based service for local development. It does two things:
- On each request it builds a fresh render.Site from disk so edits to pages/, partials/, locales/, and static/ show up without restarting the process. Template parsing happens once per request, which is fine for one developer hitting the page a few times per minute and is the simplest way to avoid an atomic-pointer reload mechanism inside render itself.
- It mounts /__reload (SSE) and /__reload.js so the browser auto-reloads when fswatch fires. The {{ devScript }} helper in web/render emits the matching <script> tag from layouts.
Never run this in production:
- cost of per-request site build is fine for one user, ruinous for real traffic;
- SSE endpoint has no auth and no rate limit;
- the reload script forces a full page refresh on every save.
Typical usage from main():
if env == "local" {
opts, _ := render.Init(os.DirFS(watchRoot)).
LoadConfig("config/config.yaml").
WithDev(true).
BuildOptions()
devSrv, _ := dev.New(dev.Options{
RenderOpts: opts,
WatchRoot: watchRoot,
})
handler = devSrv.Handler()
// devSrv satisfies system.Module — drop it into RunForever
// alongside the HTTP server module.
system.RunForever(ctx,
system.NewServer(serverOpts),
devSrv,
)
}
Index ¶
Constants ¶
const ScriptTag = `<script src="/__reload.js"></script>`
ScriptTag is what HTML responses get injected with. Exposed as a const so callers that render templates can inline it in a {{.ReloadTag}} slot instead of post-processing the output.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Broadcaster ¶
type Broadcaster interface {
// Broadcast wakes every connected subscriber. Non-blocking.
Broadcast()
// ServeSSE returns an http handler that streams reload events to
// subscribers as Server-Sent Events. eventName is the value
// written in `event:` lines (the browser ignores it for plain
// `onmessage`, but it's useful when filtering on event types).
ServeSSE(eventName string) http.HandlerFunc
}
Broadcaster is the contract HotReload needs from its underlying fan-out hub. Defined here as an interface so this module stays self-contained — callers can supply httpx.SSEHub or any other implementation (mock for tests, custom transport in prod-like staging).
type HotReload ¶
type HotReload struct {
// contains filtered or unexported fields
}
HotReload bundles everything: filesystem watcher (fswatch.Watcher), the caller's broadcast hub, the SSE endpoint, the client-side JS, and the HTML injection helper.
Typical wiring:
hub := httpx.NewSSEHub()
hr, err := dev.NewHotReloader(100*time.Millisecond, hub)
if err != nil { log.Fatal(err) }
defer hr.Close()
hr.WatchTree("static")
hr.Mount(mux) // /__reload + /__reload.js
hr.Run(ctx) // start watching
body = hr.InjectScript(body)
Not for production. Emits verbose logs, no auth, no caching — it's a local iteration tool.
Not safe for concurrent setup (call WatchTree/Mount/OnReload before Run); the broadcaster and HTML injection are safe to use from any goroutine afterward.
func NewHotReloader ¶
func NewHotReloader(debounceWindow time.Duration, hub Broadcaster) (*HotReload, error)
NewHotReloader creates a HotReload with the given debounce window and a caller-supplied broadcaster. A 100ms window collapses the 3–5 writes most editors emit per ⌘S into a single reload broadcast.
func (*HotReload) Broadcast ¶
func (h *HotReload) Broadcast()
Broadcast triggers a reload on every connected browser, bypassing the watcher loop. Useful for callers that watch *other* things (a separate config file, a NATS event, etc.) and want to piggy- back on the existing SSE client without duplicating the JS.
func (*HotReload) Close ¶
Close releases the underlying watcher. Safe to call multiple times; ignores subsequent errors.
func (*HotReload) InjectScript ¶
InjectScript splices ScriptTag right before </body>, appends to the end when no </body> is present. Use in a response-body rewriter around static file handlers so every HTML page picks up the reload loop without per-template edits.
func (*HotReload) Mount ¶
Mount registers /__reload (SSE stream) and /__reload.js (the JS client) on the given mux. Call once after setup, before Run.
func (*HotReload) OnReload ¶
func (h *HotReload) OnReload(fn func())
OnReload registers a callback fired on every detected change, before the SSE broadcast. Used by callers that need to refresh in-process state alongside the browser reload — e.g. bumping a cache-busting asset version. Multiple callbacks run in registration order. Call before Run; not safe for concurrent registration.
type Options ¶
type Options struct {
// RenderOpts is invoked once per HTTP request to produce a
// fresh render.Options. Returning the result of an in-line
// `render.Init(...).LoadConfig(...).BuildOptions()` is what
// makes config.yaml hot-reload work — every request re-parses
// the YAML from disk so edits take effect on the next refresh.
// For static dev setups, the closure can return the same value
// every time. Required.
RenderOpts func() (render.Options, error)
// WatchRoot is the directory whose subtree the dev watcher
// monitors. A change anywhere under here triggers an SSE broadcast
// and the browser reloads. Typically the service's source directory.
WatchRoot string
// DebounceWindow collapses bursty editor saves into a single
// reload. nil → 100 ms (good for VS Code, JetBrains, vim).
DebounceWindow time.Duration
}
Options configures a dev Server. Required fields fail at New() if missing; everything else gets a default appropriate for laptop dev.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the dev wrapper. Build with New, attach with Handler(), drive lifecycle with Register / Shutdown via system.RunForever.
func New ¶
New validates the options and stages the watcher (no goroutines spawned yet — Register starts the loop). Calls RenderOpts once up front so a misconfigured FS or a malformed config.yaml fails at boot, not on the first request.
func (*Server) Handler ¶
Handler returns the HTTP handler that:
- serves /__reload (SSE) and /__reload.js (the JS client) directly from the embedded HotReload mux;
- rebuilds a fresh render.Site for every other request and dispatches into it.
Compose secheaders / httplog around the result; this handler does not touch security headers or access logs by design — those are concerns of the wrapping middleware, not the dev shim.
func (*Server) Register ¶
Register starts the file-watching goroutine and returns immediately, satisfying the system.Module contract so a dev.Server drops into system.RunForever alongside the HTTP server module:
system.RunForever(ctx,
system.NewServer(serverOpts),
devServer, // last → first to Shutdown
)
ctx is the long-lived service context; the watcher exits when ctx is cancelled. Always returns nil — fsnotify's underlying handle was created in New() and any failure surfaced there.
func (*Server) Shutdown ¶
Shutdown releases the underlying fsnotify watcher. Satisfies system.ShutdownModule so RunForever's reverse-order drain frees the inotify/kqueue handle before the process exits. shutdownCtx is honoured implicitly: fsnotify.Close is fast (no I/O), so the deadline is effectively unused. Safe to call multiple times.