dev

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package dev wires hot reload onto a render-based service for local development. It does two things:

  1. 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.
  2. 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

View Source
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

func (h *HotReload) Close() error

Close releases the underlying watcher. Safe to call multiple times; ignores subsequent errors.

func (*HotReload) InjectScript

func (h *HotReload) InjectScript(body []byte) []byte

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

func (h *HotReload) Mount(mux *http.ServeMux)

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.

func (*HotReload) Run

func (h *HotReload) Run(ctx context.Context)

Run starts the event loop in a background goroutine. Cancel the ctx (e.g. via signal.NotifyContext) to stop it.

func (*HotReload) WatchTree

func (h *HotReload) WatchTree(root string) error

WatchTree adds `root` plus every subdirectory to the watcher. Thin pass-through to Watcher.AddTree — kept on this type so callers don't have to thread the Watcher around for the common case.

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

func New(opts Options) (*Server, error)

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

func (s *Server) Handler() http.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

func (s *Server) Register(ctx context.Context) error

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

func (s *Server) Shutdown(shutdownCtx context.Context) error

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL