Server-rendered apps with Go, templ and HTMX
The hypermedia approach and a first server
What the server sends and what the browser does when HTML is the wire format, compared with a JSON API, and a first net/http server.
- lesson
- 01 of 08
- read
- 9 min
The application in this course never sends JSON to its own front end. The server answers every request with HTML, either a whole page or a piece of one, and the browser puts that HTML on screen. This lesson makes the difference from a JSON API concrete with two responses from the same Go program, then leaves you with the server the rest of the course grows from.
Create the project
mkdir readinglist
cd readinglist
go mod init readinglistgo: creating new go.mod: module readinglistThe module path is a bare name because nothing will ever import this program. Now write a server that offers the same two links in two formats:
package main
import (
"encoding/json"
"flag"
"fmt"
"html"
"log"
"net/http"
)
type Link struct {
ID int64 `json:"id"`
URL string `json:"url"`
Title string `json:"title"`
Read bool `json:"read"`
}
var links = []Link{
{ID: 1, URL: "https://go.dev/blog/routing-enhancements", Title: "Routing Enhancements for Go 1.22"},
{ID: 2, URL: "https://htmx.org/essays/hypermedia-driven-applications/", Title: "Hypermedia-Driven Applications", Read: true},
}
func main() {
addr := flag.String("addr", "localhost:8792", "address to listen on")
flag.Parse()
mux := http.NewServeMux()
mux.HandleFunc("GET /api/links", linksJSON)
mux.HandleFunc("GET /links", linksHTML)
log.Printf("listening on http://%s", *addr)
log.Fatal(http.ListenAndServe(*addr, mux))
}
func linksJSON(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(links); err != nil {
log.Print(err)
}
}
func linksHTML(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, "<!doctype html>\n<title>Reading list</title>\n<h1>Reading list</h1>\n<ul>\n")
for _, l := range links {
state := "unread"
if l.Read {
state = "read"
}
fmt.Fprintf(w, " <li class=%q><a href=%q>%s</a></li>\n",
state, l.URL, html.EscapeString(l.Title))
}
fmt.Fprint(w, "</ul>\n")
}Three details matter later. The patterns passed to HandleFunc start with an HTTP method, which http.ServeMux has understood since Go 1.22. The address is a flag, so a second instance can listen on another port. And the default binds to localhost only, which keeps a development server off your network. The port number is arbitrary: 8792 stays clear of 8080 and 3000, which other development tools tend to claim.
http.ListenAndServe blocks until the server fails, so the program runs until you stop it with Ctrl+C.
go run .2026/11/28 23:41:21 listening on http://localhost:8792Two answers to the same question
In a second terminal, ask for the list both ways.
curl -s localhost:8792/api/links[{"id":1,"url":"https://go.dev/blog/routing-enhancements","title":"Routing Enhancements for Go 1.22","read":false},{"id":2,"url":"https://htmx.org/essays/hypermedia-driven-applications/","title":"Hypermedia-Driven Applications","read":true}]curl -s localhost:8792/links<!doctype html>
<title>Reading list</title>
<h1>Reading list</h1>
<ul>
<li class="unread"><a href="https://go.dev/blog/routing-enhancements">Routing Enhancements for Go 1.22</a></li>
<li class="read"><a href="https://htmx.org/essays/hypermedia-driven-applications/">Hypermedia-Driven Applications</a></li>
</ul>Both carry the same facts. What differs is how much work remains before a person can use them.
A browser can do nothing useful with the JSON. A script has to fetch it, decide what a read link looks like, build the list elements, and keep its own copy of the array so it can update the page later. To mark link 1 as read, that script also has to know, from documentation or convention, which URL to call, with which method and which body. All of that knowledge lives in client code and has to change whenever the API does.
The HTML is finished. The browser renders it without any code of yours. The decision that a read link gets class="read" was made once, on the server, next to the data. From lesson 3 on, each list item will also carry a form with the URL that toggles it, so the page itself tells the browser which actions exist and where to send them. That is the sense of “hypermedia”: the response contains the data and the controls for changing it.
Who does the work
Here is one interaction, marking a link as read, in both models.
| Step | JSON API with a client-side app | Hypermedia |
|---|---|---|
| Page load | The server sends an HTML shell and a script bundle. The script fetches /api/links and builds the list. |
The server sends the page with the list in it. |
| Click | Client code builds a request from what it knows about the API. | The browser submits the form it found in the list item. |
| Response | JSON describing the changed link. | HTML for the changed list item. |
| Afterwards | Client code updates its copy of the data and renders again. | The new HTML replaces the old item. |
The last row is the one step plain HTML cannot do: a browser on its own replaces the whole page with whatever a form returns. Lesson 4 adds htmx, a script of about 37 kB (the file is measured there) that lets an element send a request and put the response into a chosen part of the page. Until then the application works with full page loads, and it will keep working that way for a browser with scripts turned off.
The trade has two sides. Every interaction in the hypermedia model is a network round trip, so latency is visible, and nothing works offline. An interface that must react to each keystroke or drag without asking the server, such as a drawing tool or a spreadsheet grid, fits badly. A mobile app or a third-party integration cannot consume HTML fragments and would still need a JSON API.
In return, the state lives in one place, the database, and there is no API contract between your own front end and back end to version and keep in sync. Validation and access rules are written once, in the same language as everything else.
A reading list is a few forms and a list over a database, so it sits on the side where hypermedia costs little.
Keep the HTML handler
The JSON endpoint has served its purpose. Delete linksJSON, its route, the encoding/json import and the struct tags on Link. Restart the server and check both URLs:
curl -i localhost:8792/linksHTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sat, 28 Nov 2026 21:41:38 GMT
Content-Length: 316
<!doctype html>
...curl -i localhost:8792/api/linksHTTP/1.1 404 Not Found
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
...One warning about linksHTML before moving on. It assembles HTML from strings, and the only thing standing between a link title and the page is the call to html.EscapeString. Forget it for one value and that value can inject markup. The %q verb used for the attributes is worse: it produces a Go string literal, which is not HTML attribute escaping, and it is only safe here because the data is hard-coded. Lesson 3 replaces this handler with templ components, which escape every value by default.
The next lesson gives the server real routes: one handler per action, an in-memory store behind them, and logging around them.
Exercises
- Add a third link whose title is
Tags & <b>bold</b> claims. A correct result showsTags & <b>bold</b> claimsin thecurloutput and the literal text, angle brackets included, in a browser. Then remove thehtml.EscapeStringcall and reload: the word “bold” is now rendered in bold, which is the injection the call prevents. Put the call back. - Add a
GET /healthzroute that writesok.curl -i localhost:8792/healthzshould show status 200 andContent-Type: text/plain; charset=utf-8, a header you did not set (net/httpdetects the type from the body).curl -i -X POST localhost:8792/healthzshould show405 Method Not Allowedwith the headerAllow: GET, HEAD. - With the server running, start a second copy with
go run .in another terminal. It should exit withlisten tcp 127.0.0.1:8792: bind: address already in use. Start it again with-addrset to a free port and confirm that both instances answer.