go 48 lines · 8 steps

Serving embedded static assets in Go

An http.Handler serves files compiled into the binary via embed.FS, adding cache headers tuned to each file's stability.

Explained by highlit
1package web
2 
3import (
4 "embed"
5 "io/fs"
6 "net/http"
7 "strings"
8 "time"
9)
10 
11//go:embed assets/*
12var assetsFS embed.FS
13 
14func AssetsHandler() (http.Handler, error) {
15 sub, err := fs.Sub(assetsFS, "assets")
16 if err != nil {
17 return nil, err
18 }
19 
20 fileServer := http.FileServer(http.FS(sub))
21 
22 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23 upstream := strings.TrimPrefix(r.URL.Path, "/assets/")
24 if info, err := fs.Stat(sub, upstream); err != nil || info.IsDir() {
25 http.NotFound(w, r)
26 return
27 }
28 
29 if strings.Contains(upstream, ".min.") || strings.HasPrefix(upstream, "vendor/") {
30 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
31 } else {
32 w.Header().Set("Cache-Control", "public, max-age=3600")
33 }
34 
35 http.StripPrefix("/assets/", fileServer).ServeHTTP(w, r)
36 }), nil
37}
38 
39func Register(mux *http.ServeMux) error {
40 handler, err := AssetsHandler()
41 if err != nil {
42 return err
43 }
44 mux.Handle("/assets/", handler)
45 return nil
46}
47 
48var buildTime = time.Now()
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Embedding assets with go:embed ships a self-contained binary with no external file dependencies.
  2. 2Wrapping a FileServer in a closure lets you inject per-request logic like validation and cache headers.
  3. 3Match Cache-Control max-age to how often each asset actually changes to balance freshness and caching.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Serving embedded static assets in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code