Capstone 3: the built frontend

The service ships as one binary that serves both the API and the page. The page is a directory of built files, internal/web/dist, and //go:embed puts it inside the executable. There is no COPY of a static directory in the image and no path to configure: the files are the binary.

The embedded tree

The directive names the directory and the variable is an embed.FS. fs.Sub makes the dist prefix disappear, so the handler sees index.html at the root; a file server over the embedded tree is the same call as one over a disk. The build fails if the pattern matches nothing, which catches a renamed directory at compile time.

// Package web serves the built frontend from the binary. package web import ( "embed" "io/fs" "net/http" "strings" ) //go:embed dist var dist embed.FS // FS returns the built frontend as a filesystem. func FS() (fs.FS, error) { return fs.Sub(dist, "dist") } // Handler serves the frontend and falls back to index.html for a client route. func Handler() http.Handler { sub, err := fs.Sub(dist, "dist") if err != nil { panic(err) } files := http.FileServer(http.FS(sub)) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/api/") { http.NotFound(w, r) return } name := strings.TrimPrefix(r.URL.Path, "/") if name == "" { name = "index.html" } if _, err := fs.Stat(sub, name); err != nil { r = r.Clone(r.Context()) r.URL.Path = "/" } files.ServeHTTP(w, r) }) }

The handler serves the file when it exists and rewrites the request to / when it does not, which serves index.html for a client-side route. A request under /api/ is a 404 from this handler, because the API is mounted in front of it and a missing API path must not return the page as HTML.

The file handler

http.FileServer(http.FS(sub)) sets the content type, the length, the last-modified header and the range support from the filesystem, and it refuses a path that climbs out of the root. That is a lot of behaviour for one line, and it is the same code that serves a disk directory.

The client route

A single-page app has routes the server does not know: /notes/1 is a page, not a file. The fallback turns a missing file into index.html with a 200, and the client router reads the URL. A missing asset such as /missing.js gets the page too, which is a little wrong; a production server returns the page only when the path has no extension, and the exercise asks for that.

Three paths

The demo mounts the API under /api/ and the web handler at /, then asks for the root, a client route and the API. The root and the route serve the page; the API answers JSON.

package main import ( "fmt" "io" "log/slog" "net/http" "net/http/httptest" "strings" "example.com/notesapi/internal/api" "example.com/notesapi/internal/store" "example.com/notesapi/internal/web" ) func main() { a := api.New(store.NewMemory(), slog.New(slog.NewTextHandler(io.Discard, nil))) handler := a.Routes() root := http.NewServeMux() root.Handle("/api/", handler) root.Handle("/", web.Handler()) srv := httptest.NewServer(root) defer srv.Close() for _, path := range []string{"/", "/some/client/route", "/api/notes"} { resp, err := http.Get(srv.URL + path) if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Printf("%-22s %d index=%v\n", path, resp.StatusCode, strings.Contains(string(body), "<title>Notes</title>")) } }

go run ./cmd/l134

/ 200 index=true
/some/client/route 200 index=true
/api/notes 200 index=false

The root and the made-up route both returned the page, and the API returned its array. The third line shows false for the page because a JSON array does not contain the title, which is the check the demo prints instead of a page of HTML.

The frontend here

The dist directory in this lesson is a hand-written page: an index.html with a title, a list and a form, and an app.js that calls /api/notes with fetch. It is the build output a frontend tool would produce, checked in and embedded. Node and npm are not in this container, so nothing here was built by them; the React version of the same page belongs to the separate Go and React project group and is not claimed here.

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Notes</title> </head> <body> <h1>Notes</h1> <ul id="notes"></ul> <form id="add"> <input id="title" placeholder="note title" required> <button>add</button> </form> <script src="/app.js" defer></script> </body> </html>

async function load() { const list = document.getElementById("notes"); list.textContent = ""; const resp = await fetch("/api/notes"); if (!resp.ok) return; for (const note of await resp.json()) { const item = document.createElement("li"); item.textContent = note.title; list.append(item); } } document.getElementById("add").addEventListener("submit", async (event) => { event.preventDefault(); const input = document.getElementById("title"); await fetch("/api/notes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: input.value }), }); input.value = ""; load(); });

Two files are enough to show the shape: a page and a script that reads and writes the API. A real build adds hashed asset names, a CSS file and a manifest; the Go side does not change, because it serves a directory whatever is in it.

One binary, one origin

The page and the API share an origin, so the browser makes no cross-origin request and lesson 103's CORS middleware is not needed in production. The binary is the whole deployment artifact: no static directory next to it, no CDN configuration, no MIME map to keep. The cost is a binary that grows by the size of the frontend, which is small for a page and worth measuring for a large one.

The next lesson deploys this binary: configuration from the environment, a health check, a graceful stop and a Dockerfile.

Exercises

  1. Return the page only for a path without an extension and a 404 otherwise. Which function changes, and what does path.Ext return for /notes/1?
  2. Add a CSS file to dist and fetch it through the handler. Which content type does the server set, and where does it come from?
  3. Compare the binary size with and without a one-megabyte file in dist. What does the embed cost, and when would a CDN be better?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does //go:embed put in the binary?

    Answer

    The files of the pattern, as an embed.FS

    No static directory is needed.

  2. What does fs.Sub do?

    Answer

    Removes the dist prefix from the paths

    The handler sees index.html at the root.

  3. What serves the files?

    Answer

    http.FileServer over http.FS of the embedded tree

    It sets the types and the ranges.

  4. What does the fallback serve for a client route?

    Answer

    index.html with a 200

    The client router reads the URL.

  5. Why is /api/ a 404 from the web handler?

    Answer

    A missing API path must not return the page as HTML

    The API is mounted in front.

  6. What is the frontend in this lesson?

    Answer

    A hand-written page and script, since Node is not in the image

    The page says so.

  7. Why no CORS in production?

    Answer

    The page and the API share an origin

    One origin needs no header.

  8. What is the deployment artifact?

    Answer

    One binary with the page inside

    No static directory to copy.

  9. What happens if the embed pattern matches nothing?

    Answer

    The build fails

    A typo is caught at compile time.

  10. What is the cost of embedding?

    Answer

    The binary grows by the size of the files

    Usually small, worth measuring.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev