RC RANDOM CHAOS

A practical pattern for wiring HTMX into Go web apps

· via Hacker News

Original source

How I use HTMX with Go

Hacker News →

Alex Edwards walks through his approach to combining HTMX with Go for lightweight interactivity that keeps rendering on the server. The appeal is minimal hand-written JavaScript while retaining the safety and consistency of Go’s html/template package. He prefers serving HTMX as a locally downloaded static file rather than pulling from a CDN, and loads it with the defer attribute so the script fetches in parallel but only runs once the DOM is built.

The core of the piece is template organization. Edwards splits markup into a base layout, page-specific files, and reusable partials, and names every template explicitly with {{define}} for consistent reference from Go. Static assets and HTML are embedded directly into the binary using Go’s embed.FS (available since Go 1.16), then split into separate HTMLFiles and StaticFiles sub-filesystems so code only touches the files it should. A small htmlRenderer type parses shared templates at startup, then clones and extends that set per request before executing a named template.

This structure lets the same handlers serve either full pages or partial fragments, which is what HTMX needs: a button with hx-get and hx-swap swaps itself out for whatever HTML the server returns. Because partials are preloaded into the shared template set, rendering a fragment like a gopher image requires no extra file paths. The post also promises coverage of HTMX redirects, error handling, and standard configuration settings, and doubles as promotion for the author’s Go web development book.

Read the full article

Continue reading at Hacker News →

This is an AI-generated summary. Read the original for the full story.