如何对静态资源加 hash 指纹并开启 gzip?

解读

国内面试中,这道题表面问“两步操作”,实则考察候选人是否具备“性能优化 + 版本管理 + 自动化”三位一体思维。

  1. hash 指纹:解决 CDN 缓存、灰度发布、回滚问题,是“可观测性”的一部分。
  2. gzip:解决传输体积,是“可压缩性”的一部分。
  3. Beego 默认只提供静态文件服务,不帮你做“构建期”的 hash 重命名,也不自动帮你压缩;必须自己把“构建管线”与“运行时配置”打通。
    因此,面试官想听的是:
  • 你能在构建阶段用主流工具(webpack、esbuild、vite、gulp 等)把文件名改成 index.abc123.js;
  • 你能在 Beego 侧把带 hash 的文件“无感知”地映射回 HTML;
  • 你能在 Beego 侧把 gzip 开关打开,并保证走 CDN 时仍能被正确解压;
  • 你能把整条链路脚本化,让同事 make build 一把梭。

知识点

  1. 构建期 hash:内容哈希(contenthash)、chunkhash、hash 区别;文件重命名后 HTML 模板如何自动引用。
  2. Beego 静态映射:beego.SetStaticPath 与 beego.BConfig.WebConfig.StaticDir 的优先级;如何支持 embed.FS 做单二进制交付。
  3. 模板自动注入:使用 html/template 的 funcMap,在启动时把 manifest.json 读进内存,模板里写 <script src="{{asset "index.js"}}"> 即可。
  4. gzip 中间件:Beego 自带 beego.BConfig.EnableGzip=true 仅对动态响应生效;静态文件需要 StaticExtensionsToGzip 白名单 + http.FileServer 配合 gzip.NewWriterLevel;或者前置 Nginx/OpenResty 统一压缩。
  5. ETag & Cache-Control:hash 文件可给 Cache-Control: max-age=31536000, immutable,非 hash 文件必须 no-cache。
  6. 国内 CDN 踩坑:阿里云 CDN、腾讯云 ECDN 默认会“强制 gzip”,注意源站不要双压缩;回源 Host 与 SNI 保持一致。
  7. 热更新:Beego 的 bee run 只监听 .go 文件,前端 hash 变化需要自定义 bee 的 watch_ext,否则本地调试白屏。

答案

生产级落地分三步:构建、运行时、验证。

第一步:构建期生成带 hash 的静态资源
项目根目录建 web 目录,前端源码放 web/src,输出到 web/dist。
以 webpack 为例,配置:

output: {
  filename: '[name].[contenthash:8].js',
  path: path.resolve(__dirname, '../web/dist'),
  clean: true
}

同时生成 web/dist/manifest.json:

{
  "index.js": "index.3d4ab5fe.js",
  "index.css": "index.8a9c2d1d.css"
}

把 web/dist 整个目录提交到 Git 大文件存储或 CI 产物仓库,供 Go 程序打包。

第二步:Beego 启动时把 manifest 注入模板函数

package main

import (
    "embed"
    "encoding/json"
    "html/template"
    "io/fs"
    "net/http"
    "strings"

    "github.com/beego/beego/v2/server/web"
)

//go:embed web/dist/*
var distFS embed.FS

var manifest map[string]string

func init() {
    data, _ := distFS.ReadFile("web/dist/manifest.json")
    json.Unmarshal(data, &manifest)

    web.AddFuncMap("asset", func(name string) string {
        if hashed, ok := manifest[name]; ok {
            return "/static/" + hashed
        }
        return "/static/" + name
    })
}

func main() {
    // 1. 静态文件路由:把 /static 指向 embed 里的 dist
    dist, _ := fs.Sub(distFS, "web/dist")
    web.SetStaticPath("/static", "web/dist")        // 开发模式
    web.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.FS(dist))))

    // 2. 开 gzip:对静态后缀生效
    web.BConfig.EnableGzip = true
    web.BConfig.WebConfig.StaticExtensionsToGzip = []string{".js", ".css", ".svg", ".json"}

    // 3. 模板渲染
    web.Router("/", &MainController{})
    web.Run()
}

模板文件 views/index.tpl:

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="{{asset "index.css"}}">
</head>
<body>
    <script src="{{asset "index.js"}}"></script>
</body>
</html>

第三步:验证

  1. 本地 curl -H "Accept-Encoding: gzip" -I http://localhost:8080/static/index.3d4ab5fe.js,返回 Content-Encoding: gzip 且大小减少 70%+。
  2. 修改一行 JS,重新 make build,manifest 变化,模板自动引用新 hash,刷新页面 200;旧文件仍存,可实现灰度回滚。
  3. 推送到预发环境,绑定阿里云 CDN,设置“智能压缩”关闭,避免双压缩;源站只需提供 gzip 文件即可。

拓展思考

  1. 多环境差异化:测试环境不想走 hash,可以 {{if .IsProd}}{{asset "index.js"}}{{else}}/static/index.js{{end}},通过 beego.AppConfig.String("runmode") 控制。
  2. 服务端渲染(SSR):Beego 做 BFF 时,可把 manifest 注入到 window.__INITIAL_STATE__,前端同构直出,避免 FOUC。
  3. http.FS 与 gzip 性能:Go 1.20+ 支持 http.FS 直接对接 embed.FS,但每次压缩会吃 CPU;高并发场景可在构建期直接输出 .gz 文件,Beego 判断 Accept-Encoding 后直接 http.ServeContent 返回 .gz,CPU 降 80%。
  4. 版本回滚策略:在 manifest.json 里再加一个 version 字段,结合 Kubernetes 的 rollout undo,可实现“一键回滚到上一个 hash 版本”,无需重新构建。
  5. 安全 header:hash 文件长期缓存,务必加 Cache-Control: immutable 和 X-Content-Type-Options: nosniff,防止运营商缓存投毒。