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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Embedding assets with go:embed ships a self-contained binary with no external file dependencies.
- 2Wrapping a FileServer in a closure lets you inject per-request logic like validation and cache headers.
- 3Match Cache-Control max-age to how often each asset actually changes to balance freshness and caching.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/serving-embedded-static-assets-in-go-explained-go-f0d6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.