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 hashring import ( "hash/crc32"
How consistent hashing works in Go
consistent-hashing
load-balancing
concurrency
Intermediate
8 steps
go
package middleware import ( "net/http"
Wrapping Gin requests in a DB transaction
middleware
transactions
error-handling
Intermediate
8 steps
php
<?php namespace App\Http\Middleware;
Caching HTTP responses with Laravel middleware
middleware
caching
http
Intermediate
8 steps
typescript
type Countdown = { days: number; hours: number; minutes: number;
Building a self-stopping countdown timer
date-math
closures
timers
Intermediate
9 steps
go
package handlers import ( "encoding/base64"
Cursor pagination in a Gin handler
pagination
cursor
rest-api
Intermediate
8 steps
python
from django.core.cache import cache from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save, post_delete from django.dispatch import receiver
Busting template fragment caches in Django
caching
signals
cache-invalidation
Intermediate
4 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.