Server-rendered apps with Go, templ and HTMX
Routing and handlers with the standard library
ServeMux method and wildcard patterns, handlers as methods on an app struct, middleware as plain functions, and request logging with log/slog.
- lesson
- 02 of 08
- read
- 22 min
This lesson gives the reading list its HTTP surface: one route per action, handlers that share their dependencies through a struct, an in-memory store behind them and two middleware functions around them. Responses are plain text for now, which keeps the attention on routing. Everything used here is in the standard library.
A store to route to
Handlers need something to call. The hard-coded slice from lesson 1 becomes a store in its own file:
package main
import (
"context"
"errors"
"slices"
"strings"
"sync"
"time"
)
type Link struct {
ID int64
URL string
Title string
Note string
Read bool
CreatedAt time.Time
}
// Filter narrows List. The zero value matches every link.
type Filter struct {
Query string // substring of the title, URL or note
Status string // "unread" or "read"; anything else means both
}
var ErrNotFound = errors.New("link not found")
// Store keeps links in memory, newest first.
type Store struct {
mu sync.Mutex
links []Link
nextID int64
}
func NewStore() *Store {
return &Store{nextID: 1}
}
func (s *Store) List(ctx context.Context, f Filter) ([]Link, error) {
s.mu.Lock()
defer s.mu.Unlock()
q := strings.ToLower(f.Query)
var out []Link
for _, l := range s.links {
if f.Status == "unread" && l.Read || f.Status == "read" && !l.Read {
continue
}
if q != "" && !strings.Contains(strings.ToLower(l.Title+" "+l.URL+" "+l.Note), q) {
continue
}
out = append(out, l)
}
return out, nil
}
func (s *Store) Get(ctx context.Context, id int64) (Link, error) {
s.mu.Lock()
defer s.mu.Unlock()
i := s.index(id)
if i < 0 {
return Link{}, ErrNotFound
}
return s.links[i], nil
}
func (s *Store) Create(ctx context.Context, url, title, note string) (Link, error) {
s.mu.Lock()
defer s.mu.Unlock()
l := Link{ID: s.nextID, URL: url, Title: title, Note: note, CreatedAt: time.Now()}
s.nextID++
s.links = slices.Insert(s.links, 0, l)
return l, nil
}
func (s *Store) ToggleRead(ctx context.Context, id int64) (Link, error) {
s.mu.Lock()
defer s.mu.Unlock()
i := s.index(id)
if i < 0 {
return Link{}, ErrNotFound
}
s.links[i].Read = !s.links[i].Read
return s.links[i], nil
}
func (s *Store) Delete(ctx context.Context, id int64) error {
s.mu.Lock()
defer s.mu.Unlock()
i := s.index(id)
if i < 0 {
return ErrNotFound
}
s.links = slices.Delete(s.links, i, i+1)
return nil
}
func (s *Store) index(id int64) int {
return slices.IndexFunc(s.links, func(l Link) bool { return l.ID == id })
}Nothing in this file knows about HTTP. Every method takes a context.Context first and returns an error last, although a slice in memory needs neither. That is deliberate. It is the signature a database-backed store needs, so lesson 6 can replace the method bodies with SQL without rewriting the handlers. ErrNotFound is a sentinel value the handlers translate into a 404.
Handlers as methods
The handlers need the store and a logger. Package-level variables would work, but a struct makes the dependencies explicit and lets a test build its own instance.
package main
import (
"errors"
"fmt"
"log/slog"
"net/http"
"strconv"
)
type app struct {
logger *slog.Logger
store *Store
}
func (a *app) listLinks(w http.ResponseWriter, r *http.Request) {
f := Filter{
Query: r.URL.Query().Get("q"),
Status: r.URL.Query().Get("filter"),
}
links, err := a.store.List(r.Context(), f)
if err != nil {
a.serverError(w, r, err)
return
}
for _, l := range links {
fmt.Fprintln(w, formatLink(l))
}
}
func (a *app) showLink(w http.ResponseWriter, r *http.Request) {
id, ok := pathID(r)
if !ok {
http.NotFound(w, r)
return
}
l, err := a.store.Get(r.Context(), id)
if err != nil {
a.storeError(w, r, err)
return
}
fmt.Fprintln(w, formatLink(l))
}
func (a *app) createLink(w http.ResponseWriter, r *http.Request) {
l, err := a.store.Create(r.Context(),
r.PostFormValue("url"), r.PostFormValue("title"), r.PostFormValue("note"))
if err != nil {
a.serverError(w, r, err)
return
}
a.logger.Info("link created", "id", l.ID)
http.Redirect(w, r, "/links", http.StatusSeeOther)
}
func (a *app) toggleLink(w http.ResponseWriter, r *http.Request) {
id, ok := pathID(r)
if !ok {
http.NotFound(w, r)
return
}
if _, err := a.store.ToggleRead(r.Context(), id); err != nil {
a.storeError(w, r, err)
return
}
http.Redirect(w, r, "/links", http.StatusSeeOther)
}
func (a *app) deleteLink(w http.ResponseWriter, r *http.Request) {
id, ok := pathID(r)
if !ok {
http.NotFound(w, r)
return
}
if err := a.store.Delete(r.Context(), id); err != nil {
a.storeError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// pathID reads the {id} wildcard as a positive integer.
func pathID(r *http.Request) (int64, bool) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
return id, err == nil && id > 0
}
func formatLink(l Link) string {
mark := " "
if l.Read {
mark = "x"
}
return fmt.Sprintf("%d [%s] %s <%s>", l.ID, mark, l.Title, l.URL)
}
func (a *app) storeError(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, ErrNotFound) {
http.NotFound(w, r)
return
}
a.serverError(w, r, err)
}
func (a *app) serverError(w http.ResponseWriter, r *http.Request, err error) {
a.logger.Error("request failed", "method", r.Method, "path", r.URL.Path, "err", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}Every handler has the same shape: read the input, call the store, write a response. The input comes from three places. r.URL.Query() holds the query string. r.PostFormValue reads a field from the request body and ignores the query string. r.PathValue("id") returns the text that matched {id} in the route pattern, always as a string, so pathID converts it and treats anything that is not a positive integer as a link that does not exist.
createLink and toggleLink answer with 303 See Other, which tells the client to fetch /links with a GET. Lesson 5 explains why a form submission should end that way. There is no validation yet either, so an empty title is accepted. That also waits for lesson 5.
serverError writes the real error to the log and a generic message to the client. Error text can contain file paths, SQL or other internals and does not belong in a response.
Route patterns
package main
import "net/http"
func (a *app) routes() http.Handler {
mux := http.NewServeMux()
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("POST /links/{id}/toggle", a.toggleLink)
mux.HandleFunc("DELETE /links/{id}", a.deleteLink)
return a.logRequests(a.recoverPanic(mux))
}A pattern is an optional method, a space and a path. The rules that matter for this application:
- A pattern with a method matches only that method, except that
GETalso matchesHEAD. If the path matches but the method does not, the mux answers405 Method Not Allowedand lists the methods that would have worked. {id}matches exactly one path segment.GET /links/{id}does not match/links/or/links/3/extra.- A path ending in a slash matches everything below it, so
GET /would be a catch-all.{$}anchors the pattern:GET /{$}matches the root and nothing else. - When two patterns match a request, the more specific one wins, whatever the order of registration.
GET /links/newwould take precedence overGET /links/{id}.
If two patterns overlap and neither is more specific, registration panics. Adding mux.HandleFunc("GET /{section}/new", a.listLinks) to the routes above stops the program before it serves a request (file paths shortened):
panic: pattern "GET /{section}/new" (registered at routes.go:14) conflicts with pattern "GET /links/{id}" (registered at routes.go:11):
GET /{section}/new and GET /links/{id} both match some paths, like "/links/new".
But neither is more specific than the other.
GET /{section}/new matches "/section/new", but GET /links/{id} doesn't.
GET /links/{id} matches "/links/id", but GET /{section}/new doesn't.An ambiguous route table therefore fails at startup, before it can misroute a request. The ServeMux documentation has the full rules, and the article The standard library router is enough discusses where this router stops being sufficient.
Middleware
A middleware is a function that takes a handler and returns a handler. No interface or library is involved.
package main
import (
"net/http"
"runtime/debug"
"time"
)
// statusRecorder remembers the status code a handler wrote.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (rec *statusRecorder) WriteHeader(code int) {
rec.status = code
rec.ResponseWriter.WriteHeader(code)
}
// Unwrap lets http.ResponseController reach the underlying writer.
func (rec *statusRecorder) Unwrap() http.ResponseWriter {
return rec.ResponseWriter
}
func (a *app) logRequests(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
a.logger.Info("request",
"method", r.Method,
"path", r.URL.Path,
"pattern", r.Pattern,
"status", rec.status,
"duration", time.Since(start),
)
})
}
func (a *app) recoverPanic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
v := recover()
if v == nil {
return
}
if v == http.ErrAbortHandler {
panic(v)
}
a.logger.Error("panic", "value", v, "stack", string(debug.Stack()))
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}()
next.ServeHTTP(w, r)
})
}logRequests needs the status code, which http.ResponseWriter does not expose, so it wraps the writer in a statusRecorder that remembers it. The log entry also includes r.Pattern (Go 1.23 and later), the pattern the mux matched. Grouping by pattern rather than by path keeps /links/1 and /links/2 in the same bucket when you count or time requests.
recoverPanic turns a panic in a handler into a 500 response and a log entry. Without it, net/http still recovers the panic, but it closes the connection without answering, and the client sees an empty reply. http.ErrAbortHandler is the one panic value the server expects to receive, so the middleware passes it on.
In routes, the call a.logRequests(a.recoverPanic(mux)) reads from the outside in: a request passes through logging, then recovery, then the mux. Logging is outermost so that it also records the 500 that recovery writes.
Logging and wiring
What is left of main.go builds the pieces and starts the server. Replace the file from lesson 1 with this:
package main
import (
"context"
"flag"
"log/slog"
"net/http"
"os"
)
func main() {
addr := flag.String("addr", "localhost:8792", "address to listen on")
flag.Parse()
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
a := &app{logger: logger, store: NewStore()}
seed(a.store)
logger.Info("listening", "addr", *addr)
if err := http.ListenAndServe(*addr, a.routes()); err != nil {
logger.Error("server stopped", "err", err)
os.Exit(1)
}
}
// seed adds two links so the list is not empty after a restart.
func seed(s *Store) {
ctx := context.Background()
s.Create(ctx, "https://htmx.org/essays/hypermedia-driven-applications/",
"Hypermedia-Driven Applications", "The architecture this app follows.")
s.Create(ctx, "https://go.dev/blog/routing-enhancements",
"Routing Enhancements for Go 1.22", "")
}log/slog writes structured records: a message plus key-value pairs. The text handler prints them as key=value, which is readable in a terminal. slog.NewJSONHandler is a drop-in replacement when a log collector will read the output. The seed function is temporary. It saves retyping test data after every restart and goes away when the database arrives.
Try the routes
go run .curl localhost:8792/links2 [ ] Routing Enhancements for Go 1.22 <https://go.dev/blog/routing-enhancements>
1 [ ] Hypermedia-Driven Applications <https://htmx.org/essays/hypermedia-driven-applications/>Create a link, mark link 2 as read, then filter:
curl -i -d url=https://pkg.go.dev/net/http -d title=net/http localhost:8792/linksHTTP/1.1 303 See Other
Location: /links
Date: Sat, 28 Nov 2026 22:10:33 GMT
Content-Length: 0curl -i -X POST localhost:8792/links/2/toggle
curl -s 'localhost:8792/links?q=go&filter=read'2 [x] Routing Enhancements for Go 1.22 <https://go.dev/blog/routing-enhancements>A method the route table does not know for that path:
curl -i -X PUT localhost:8792/links/3HTTP/1.1 405 Method Not Allowed
Allow: DELETE, GET, HEAD
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Sat, 28 Nov 2026 22:10:33 GMT
Content-Length: 19
Method Not Allowedcurl -i localhost:8792/links/abc returns 404, and curl -i -X DELETE localhost:8792/links/3 returns 204 No Content. The server’s terminal shows one record per request:
time=2026-11-29T00:10:33.200+02:00 level=INFO msg="link created" id=3
time=2026-11-29T00:10:33.200+02:00 level=INFO msg=request method=POST path=/links pattern="POST /links" status=303 duration=111.875µs
time=2026-11-29T00:10:33.209+02:00 level=INFO msg=request method=POST path=/links/2/toggle pattern="POST /links/{id}/toggle" status=303 duration=18.292µs
time=2026-11-29T00:10:33.229+02:00 level=INFO msg=request method=PUT path=/links/3 pattern="" status=405 duration=36.959µs
time=2026-11-29T00:10:33.235+02:00 level=INFO msg=request method=GET path=/links/abc pattern="GET /links/{id}" status=404 duration=9.375µsThe 405 has an empty pattern because no route matched. The 404 for /links/abc has one: the route matched, and the handler decided the link does not exist.
The application now does everything a reading list needs except show itself to a person. The next lesson replaces the text output with HTML rendered by templ.
Exercises
- Add a route
GET /boomwhose handler callspanic("boom").curl -i localhost:8792/boomshould return500 Internal Server Error, and the log should contain alevel=ERROR msg=panicrecord with a stack trace followed by the usual request record withstatus=500. Then changeroutesto returna.logRequests(mux)and repeat: curl now reportsEmpty reply from server(exit code 52). Restore the middleware afterwards. - Write a
requestIDmiddleware that generates a random identifier per request (crypto/rand.Textis enough), sets it as theX-Request-IDresponse header, and makelogRequestsinclude it. A correct result shows the header incurl -i(Go writes it asX-Request-Id) and the same value asrequest_id=in the log record for that request. - Add a
-log-formatflag that switches between the text and JSON handlers. With-log-format json, each record should be one JSON object per line with the keystime,level,msgand the attributes, anddurationbecomes a number of nanoseconds.