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 middleware import ( "context"
Correlation ID tracing middleware in Gin
middleware
request tracing
structured logging
Intermediate
7 steps
javascript
function createCountdownTimer(durationSeconds, { onTick, onComplete } = {}) { let remaining = durationSeconds; let intervalId = null;
Building a countdown timer with closures
closures
factory-function
timers
Intermediate
9 steps
go
package pipeline import "sync"
The fan-in pattern in Go channels
concurrency
channels
fan-in
Advanced
8 steps
go
package feed import ( "encoding/json"
Streaming a JSON array in Go
streaming
json
decoder
Intermediate
6 steps
ruby
class SearchIndexReconciler DEBOUNCE_WINDOW = 5.seconds def self.schedule(record)
Debouncing search reindex jobs in Rails
debouncing
background-jobs
caching
Advanced
7 steps
javascript
const crypto = require('crypto'); function securityHeaders(options = {}) { const {
A configurable security-headers middleware in Express
middleware
http-headers
content-security-policy
Intermediate
7 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.