如何缓存静态文件并压缩?
解读
在国内一线/二线互联网公司的 Go 后端面试中,这道题常被用来区分“只会写接口”与“能独立做性能调优”的候选人。
面试官真正想听到的是:
- 你能否把“静态文件”与“动态接口”区分开,给出可落地的缓存策略;
- 你是否理解浏览器缓存、CDN 边缘缓存、服务端压缩三者的协作关系;
- 你是否能在 Gin 里用最少代码把“强缓存 + 协商缓存 + gzip/br 压缩”一次性配好,并给出可灰度、可回滚、可观测的部署方案。
回答时切忌只贴router.Static(),否则会被追问“缓存头怎么打”“压缩级别怎么调”“版本号变了怎么办”。
知识点
- HTTP 缓存模型
- 强缓存:Cache-Control max-age / Expires
- 协商缓存:ETag + If-None-Match、Last-Modified + If-Modified-Since
- 内容压缩
- 编码:gzip、brotli(br)
- 级别:gzip 1–9,br 1–11;国内通常 gzip=6,br=4,兼顾 CPU 与收益
- Gin 内置能力
StaticFileFS()/StaticFile():可注入自定义http.FileSystemgin-contrib/gzip:官方中间件,支持自定义级别与 MIME 过滤c.Header():可动态写入缓存头
- 国内特殊场景
- 微信、钉钉内置浏览器对 br 支持不完整,需做 UA 嗅探回退 gzip
- 阿里云 OSS + CDN 场景下,源站只需提供高压缩版本,边缘节点自动缓存
- 灰度发布:文件名带 contenthash,例如
app.abc123.js,配合immutable指令,版本更新直接换文件名,避免缓存雪崩
答案
下面给出一份可直接落地的生产级代码,覆盖“缓存 + 压缩 + 版本号 + 回滚”四个维度,全部用标准库与 Gin 生态完成,不依赖外部代理。
package main
import (
"crypto/md5"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)
const (
staticDir = "./dist" // 前端构建产物目录
maxAge = 365 * 24 * 3600 // 1 年
gzipLevel = gzip.DefaultCompression
enableBrotli = true // 国内若需兼容老旧微信,可改为 false
)
// 1. 自定义 FileSystem,用于在文件名中嵌入 contenthash
type hashedFS struct {
root http.FileSystem
}
func (fs *hashedFS) Open(name string) (http.File, error) {
// 去掉 url 中的 hash 段,映射到真实文件
clean := strings.Split(name, ".")[0] + filepath.Ext(name)
return fs.root.Open(clean)
}
// 2. 计算文件 ETag(md5)
func calcETag(path string) string {
f, err := os.Open(path)
if err != nil {
return ""
}
defer f.Close()
h := md5.New()
io.Copy(h, f)
return fmt.Sprintf(`"%x"`, h.Sum(nil))
}
// 3. 缓存控制中间件
func cacheControl() gin.HandlerFunc {
return func(c *gin.Context) {
// 只对静态资源生效
if !strings.HasPrefix(c.Request.URL.Path, "/static/") {
c.Next()
return
}
// 强缓存一年,且不允许重新验证
c.Header("Cache-Control", fmt.Sprintf("public, max-age=%d, immutable", maxAge))
// 协商缓存备用
path := filepath.Join(staticDir, strings.TrimPrefix(c.Request.URL.Path, "/static/"))
if etag := calcETag(path); etag != "" {
c.Header("ETag", etag)
}
c.Next()
}
}
func main() {
r := gin.New()
r.Use(gin.Recovery())
// 顺序:先压缩,后缓存
r.Use(gzip.Gzip(gzipLevel))
if enableBrotli {
r.Use(brotliMiddleware()) // 下面给出简易实现
}
r.Use(cacheControl())
// 4. 注册带 hash 的静态路由
r.StaticFS("/static", &hashedFS{http.Dir(staticDir)})
// 5. 兜底 index.html 永不缓存
r.NoRoute(func(c *gin.Context) {
c.Header("Cache-Control", "no-store")
c.File(filepath.Join(staticDir, "index.html"))
})
_ = r.Run(":8080")
}
// 简易 brotli 中间件(生产可用 github.com/andybalholm/brotli)
func brotliMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
if !strings.Contains(c.GetHeader("Accept-Encoding"), "br") {
c.Next()
return
}
c.Writer.Header().Set("Content-Encoding", "br")
c.Writer = &brotliWriter{ResponseWriter: c.Writer}
c.Next()
}
}
type brotliWriter struct {
gin.ResponseWriter
}
func (w *brotliWriter) WriteString(s string) (int, error) {
return w.Write([]byte(s))
}
部署步骤
- 前端构建时开启
output.filename = '[name].[contenthash:8].js',保证文件名随内容变化。 - 将
dist目录打进 Docker 镜像,镜像标签与 Git commit 一致,方便回滚。 - 阿里云 CDN 回源到
8080,开启“压缩跟随源站”,边缘节点自动缓存一年。 - 上线后通过
curl -H "Accept-Encoding: br" -I验证content-encoding: br与cache-control: immutable同时存在。
拓展思考
- 灰度发布
如果只想让 10% 用户体验新静态资源,可在 Nginx 层按 Cookie 或 Header 分流,两套文件名共存,回滚只需改流量比例。 - Server Push(HTTP/2)
Gin 本身不处理 h2 push,可在 Ingress-Nginx 用nginx.ingress.kubernetes.io/server-push: "/static/app.xxx.js",减少首屏 RTT。 - 压缩性能调优
在 16 核 32 G 的容器里,gzip=6 单核可压 120 MB/s,br=4 仅 40 MB/s;若 CPU 吃紧,可预压缩构建产物,服务端直接返回.gz/.br文件,CPU 占用降为零。 - 安全
带 hash 的文件务必开启immutable,防止中间人篡改重验证;同时设置X-Content-Type-Options: nosniff,避免 MIME 嗅探攻击。