valfz

Server-rendered apps with Go, templ and HTMX

Testing and shipping

Handler and fragment tests with httptest, static files embedded in the binary, cross-origin protection, graceful shutdown, and a single file to deploy.

lesson
08 of 08
read
18 min

The application works when you click through it. This lesson makes that checkable with tests that run in well under a second, removes the dependency on the working directory, refuses writes from other sites, stops the server in an orderly way, and produces one file you can copy to another machine.

Test through the handler chain

An HTML application has no API to test against, but it does not need one. Its interface is HTTP requests and the markup that comes back.

app_test.go
package main

import (
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"net/url"
	"path/filepath"
	"strings"
	"testing"
)

// newTestApp returns an app backed by a fresh database in a temporary directory.
func newTestApp(t *testing.T) *app {
	t.Helper()
	store, err := OpenStore(t.Context(), filepath.Join(t.TempDir(), "test.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { store.Close() })
	return &app{logger: slog.New(slog.DiscardHandler), store: store}
}

// send runs one request through the full handler chain. With partial set, the
// request carries the headers htmx adds when it targets part of the page.
func send(t *testing.T, a *app, method, target string, form url.Values, partial bool) *httptest.ResponseRecorder {
	t.Helper()
	var body io.Reader
	if form != nil {
		body = strings.NewReader(form.Encode())
	}
	req := httptest.NewRequest(method, target, body)
	if form != nil {
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}
	if partial {
		req.Header.Set("HX-Request", "true")
		req.Header.Set("HX-Request-Type", "partial")
	}
	rec := httptest.NewRecorder()
	a.routes().ServeHTTP(rec, req)
	return rec
}

func wantStatus(t *testing.T, rec *httptest.ResponseRecorder, want int) {
	t.Helper()
	if rec.Code != want {
		t.Fatalf("status = %d, want %d\nbody: %s", rec.Code, want, rec.Body)
	}
}

func wantBody(t *testing.T, rec *httptest.ResponseRecorder, substrings ...string) {
	t.Helper()
	for _, s := range substrings {
		if !strings.Contains(rec.Body.String(), s) {
			t.Errorf("body does not contain %q\nbody: %s", s, rec.Body)
		}
	}
}

func TestListPageAndFragment(t *testing.T) {
	a := newTestApp(t)

	page := send(t, a, "GET", "/links", nil, false)
	wantStatus(t, page, http.StatusOK)
	wantBody(t, page, "<!doctype html>", `<form id="add-link"`, `<ul id="links"`)

	fragment := send(t, a, "GET", "/links", nil, true)
	wantStatus(t, fragment, http.StatusOK)
	if got := fragment.Body.String(); !strings.HasPrefix(got, `<ul id="links"`) {
		t.Errorf("fragment starts with %.40q, want the list element", got)
	}
}

func TestCreateLink(t *testing.T) {
	a := newTestApp(t)
	form := url.Values{"url": {"https://go.dev/doc/"}, "title": {"Go <docs>"}}

	rec := send(t, a, "POST", "/links", form, true)
	wantStatus(t, rec, http.StatusCreated)
	wantBody(t, rec,
		`<li id="link-1">`,
		"Go &lt;docs&gt;",
		`<form id="add-link"`,
		`<p id="counter" hx-swap-oob="true">1 unread of 1</p>`,
	)
}

func TestCreateLinkPlainForm(t *testing.T) {
	a := newTestApp(t)
	form := url.Values{"url": {"https://go.dev/doc/"}, "title": {"Go docs"}}

	rec := send(t, a, "POST", "/links", form, false)
	wantStatus(t, rec, http.StatusSeeOther)
	if loc := rec.Header().Get("Location"); loc != "/links" {
		t.Errorf("Location = %q, want /links", loc)
	}
}

func TestCreateLinkInvalid(t *testing.T) {
	a := newTestApp(t)
	form := url.Values{"url": {"ftp://example.com/file"}, "title": {"  "}}

	rec := send(t, a, "POST", "/links", form, true)
	wantStatus(t, rec, http.StatusUnprocessableEntity)
	wantBody(t, rec,
		"Enter a full http or https URL.",
		"Enter a title.",
		`value="ftp://example.com/file"`,
	)

	links, err := a.store.List(t.Context(), Filter{})
	if err != nil {
		t.Fatal(err)
	}
	if len(links) != 0 {
		t.Errorf("store has %d links after a rejected submission, want 0", len(links))
	}
}

newTestApp gives every test a real SQLite database in a temporary directory that the testing package removes afterwards. There is no interface to mock, and the SQL is exercised along with everything else. A file is used instead of SQLite’s :memory: name for a reason: each connection in the pool would open its own empty in-memory database. A two-connection experiment confirms it, the second connection failing with no such table.

send passes a request to a.routes() and records the answer with httptest.NewRecorder. No port is opened. The request goes through the mux patterns, the middleware, the handler, the templ components and the store, which is everything except the network.

A fragment test is an ordinary request with one header. TestListPageAndFragment asks for the same URL twice and checks that it gets a document once and a bare <ul> once. TestCreateLink checks the three parts of the htmx response from lesson 7, and that the title was escaped. TestCreateLinkInvalid checks the status, the messages, the preserved input, and that nothing reached the store.

The assertions look for small, stable substrings: an id, a message, a status. Comparing whole responses would break on every change to the markup. When a test needs to reason about structure, parse the HTML instead of matching more text.

go test ./...
ok  	readinglist	0.331s

To see a failure, misspell the header value in isPartial as "Partial" and run the tests again:

--- FAIL: TestListPageAndFragment (0.01s)
    app_test.go:72: fragment starts with "<!doctype html><html lang=\"en\"><head><me", want the list element
--- FAIL: TestCreateLink (0.00s)
    app_test.go:81: status = 303, want 201
        body: 
FAIL
FAIL	readinglist	0.309s
FAIL

That one-character mistake sends htmx the redirects and full pages meant for plain browsers, the failure described in lesson 5, while the page itself still loads without complaint. go test -race ./... also passes and is worth running in CI, since handlers run concurrently.

Embed the static files

http.Dir("static") ties the binary to the directory it was started from. The embed package compiles the files into the executable instead. Replace routes.go:

routes.go
package main

import (
	"embed"
	"net/http"
	"time"
)

//go:embed static
var staticFiles embed.FS

func (a *app) routes() http.Handler {
	mux := http.NewServeMux()

	mux.Handle("GET /static/", http.FileServerFS(staticFiles))

	mux.Handle("GET /{$}", http.RedirectHandler("/links", http.StatusSeeOther))
	mux.HandleFunc("GET /links", a.listLinks)
	mux.HandleFunc("POST /links", a.createLink)
	mux.HandleFunc("GET /links/{id}", a.showLink)
	mux.HandleFunc("GET /links/{id}/edit", a.editLink)
	mux.HandleFunc("PUT /links/{id}", a.updateLink)
	mux.HandleFunc("POST /links/{id}/toggle", a.toggleLink)
	mux.HandleFunc("DELETE /links/{id}", a.deleteLink)

	sameOrigin := http.NewCrossOriginProtection()

	return deadline(5*time.Second, a.logRequests(a.recoverPanic(sameOrigin.Handler(mux))))
}

The //go:embed static comment fills staticFiles with the directory at build time. The embedded paths keep their static/ prefix, so http.FileServerFS can serve /static/htmx.min.js directly and http.StripPrefix is no longer needed.

There are two costs. A change to the stylesheet now needs a rebuild, which go run . does anyway. And embedded files carry no modification time, so responses lose the Last-Modified header that lets a browser revalidate cheaply. An exercise below deals with that.

Refuse cross-origin writes

The other new line in routes matters more than its size suggests. The server has no login and listens on localhost, and neither is a defense against a browser: any web page you visit can contain a form that posts to http://localhost:8792/links. http.CrossOriginProtection (Go 1.25 and later) rejects requests with an unsafe method when the browser reports them as cross-origin, using the Sec-Fetch-Site header or a comparison of Origin and Host.

curl -i -H 'Sec-Fetch-Site: cross-site' -d url=https://evil.example/ -d title=Injected localhost:8792/links
HTTP/1.1 403 Forbidden
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Sat, 28 Nov 2026 22:07:06 GMT
Content-Length: 57

cross-origin request detected from Sec-Fetch-Site header

Requests that carry neither header, such as curl’s or the tests’, pass. So do all GET requests, which is one more reason never to change state in a GET handler. See the type’s documentation for trusted origins and exceptions.

Shut down gracefully

Until now, Ctrl+C killed the process wherever it was. Replace main.go:

main.go
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	addr := flag.String("addr", "localhost:8792", "address to listen on")
	dbPath := flag.String("db", "readinglist.db", "path to the SQLite database file")
	flag.Parse()

	logger := slog.New(slog.NewTextHandler(os.Stderr, nil))

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	if err := run(ctx, *addr, *dbPath, logger); err != nil {
		logger.Error("exiting", "err", err)
		os.Exit(1)
	}
}

// run serves until ctx is canceled, then shuts down in order: stop accepting
// connections, let requests in flight finish, close the database.
func run(ctx context.Context, addr, dbPath string, logger *slog.Logger) error {
	store, err := OpenStore(ctx, dbPath)
	if err != nil {
		return fmt.Errorf("open store: %w", err)
	}
	defer store.Close()

	a := &app{logger: logger, store: store}
	srv := &http.Server{
		Addr:              addr,
		Handler:           a.routes(),
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      15 * time.Second,
		IdleTimeout:       time.Minute,
	}

	serveErr := make(chan error, 1)
	go func() {
		logger.Info("listening", "addr", addr, "db", dbPath)
		serveErr <- srv.ListenAndServe()
	}()

	select {
	case err := <-serveErr:
		return err
	case <-ctx.Done():
	}

	logger.Info("shutting down")
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		return fmt.Errorf("shutdown: %w", err)
	}
	if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	return nil
}

signal.NotifyContext returns a context that is canceled on Ctrl+C or SIGTERM. The server runs in a goroutine, and run waits for one of two things: ListenAndServe failing, for instance because the port is taken, or the signal.

On a signal, Shutdown stops accepting connections and waits for requests in flight, up to the ten seconds its context allows. ListenAndServe then returns http.ErrServerClosed, the expected outcome. Last, the deferred store.Close runs. With a handler that sleeps three seconds, a request already in progress when the signal arrived still completed with 200 before the process exited.

The explicit http.Server also sets timeouts. http.ListenAndServe has none, which lets a slow or stalled client hold a connection open indefinitely.

Build one binary

templ generate
go vet ./...
go test ./...
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o readinglist .

-trimpath removes local file paths from the binary, and -s -w drops the symbol table and debug information. On darwin/arm64, wc -c reports 10952498 bytes for this build and 16527794 for a plain go build.

Because the SQLite driver is Go, building for another platform needs no cross-compiler:

GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o readinglist-linux-amd64 .
file readinglist readinglist-linux-amd64
readinglist:             Mach-O 64-bit executable arm64
readinglist-linux-amd64: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, Go BuildID=iQsaF0RaXTFsnPksbznL/op4eF6j344TuiKNK8BMw/E2qVu1BS1qJDOhNHghMo/2fcX9zbTOfTQ0-jWFETH, BuildID[sha1]=6e33486335a38ce640a5ea55f3f2cc6c80b1d803, stripped

Start the native binary from an empty directory, with no static folder in sight:

/path/to/readinglist -db links.db

From another terminal:

curl -sI localhost:8792/static/htmx.min.js
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Length: 37477
Content-Type: text/javascript; charset=utf-8
Date: Sat, 28 Nov 2026 22:07:06 GMT

After creating a link, the directory holds links.db, links.db-shm and links.db-wal. Send the process an interrupt and the log ends like this:

time=2026-11-29T00:07:06.745+02:00 level=INFO msg="shutting down"

The exit status is 0, and only links.db is left: closing the database folded the write-ahead log back into the main file.

That file and the binary are the whole deployment. The server needs a directory it can write to and an address to listen on. If it should be reachable from other machines, change -addr and put it behind a reverse proxy that terminates TLS and adds authentication, because the application has none.

Exercises

  1. Write three more tests with the helpers above. A second submission of the same URL from a plain form should give 422 and a full page containing “This link is already on the list.” A partial DELETE /links/42 on an empty database should give 404 and the header HX-Retarget: #flash. After creating a link, a partial toggle should return an item with class="read" and a counter reading “0 unread of 1”.
  2. Make the static files cacheable. Wrap the file server in a middleware that sets Cache-Control: public, max-age=31536000, immutable, and add a version to the URLs in the layout, such as /static/htmx.min.js?v=4.0.2, so that an upgrade changes the URL. A correct result shows the header in curl -sI localhost:8792/static/htmx.min.js.
  3. Watch a graceful shutdown work, then fail. Add a temporary route whose handler sleeps for three seconds, request it with curl and press Ctrl+C in the server’s terminal while it is pending. The request should still return 200 and the process should exit with status 0. Then lower the shutdown timeout to one second and repeat: the log should end with err="shutdown: context deadline exceeded", the exit status should be 1, and curl should report an empty reply.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are