用标准库实现原生 HTTP/2 Server Push 并评估缓存命中率提升
解读
国内云原生面试高频考点,“会不会用标准库做 Server Push” 直接区分“只写 CRUD”与“懂高性能网关”的候选人。
题目隐含三层要求:
- 零第三方依赖,只能用
net/http与golang.org/x/net/http2; - 可观测,必须给出可量化的缓存命中率提升指标;
- 可灰度,支持按 Header 或 Query 参数开关 Push,方便线上 A/B。
知识点
- http.Pusher 接口:Go 1.8+ 标准库唯一入口,需 TLS 或
h2c明文协商。 - 缓存键设计:以
ETag + Last-Modified做强验证器,避免误命中。 - Vary 头:必须带
Vary: Accept-Encoding,否则 CDN 会把 gzip 与明文混用导致命中率失真。 - Prometheus 自定义指标:用
prometheus.NewCounterVec记录push_total、push_hit_total,命中率 = push_hit_total / push_total。 - h2c 降级:国内部分老旧 SLB 只透传 80 端口,需支持明文 HTTP/2,用
golang.org/x/net/http2/h2c包一层 Handler。 - 资源优先级:对关键 CSS 用
Link: </main.css>; rel=preload; as=style,优先级最高;次要图片用as=image并加nopush参数做对比组。
答案
package main
import (
"crypto/tls"
"expvar"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)
var (
pushTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http2_push_total",
Help: "Total number of attempted server pushes",
}, []string{"resource"})
pushHit = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http2_push_hit_total",
Help: "Number of pushes that hit browser cache (304)",
}, []string{"resource"})
)
func init() {
prometheus.MustRegister(pushTotal, pushHit)
expvar.Publish("cache_hit_ratio", expvar.Func(cacheHitRatio))
}
func cacheHitRatio() interface{} {
total := 0.0
hit := 0.0
for _, r := range []string{"main.css", "app.js"} {
total += pushTotal.WithLabelValues(r).(prometheus.Counter).Get()
hit += pushHit.WithLabelValues(r).(prometheus.Counter).Get()
}
if total == 0 {
return 0
}
return hit / total
}
func main() {
mux := http.NewServeMux()
// 关键资源带版本号 ?v=hash,确保更新即失效
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
// 仅对支持 Push 且未禁用(?nopush=1)的客户端生效
if pusher, ok := w.(http.Pusher); ok && r.URL.Query().Get("nopush") == "" {
for _, res := range []string{"/static/main.css?v=1a2b3c", "/static/app.js?v=4d5e6f"} {
if err := pusher.Push(res, nil); err == nil {
pushTotal.WithLabelValues(res).Inc()
}
}
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, `<!doctype html>
<html>
<head><link rel="stylesheet" href="/static/main.css?v=1a2b3c"></head>
<body><script src="/static/app.js?v=4d5e6f"></script></body>
</html>`)
})
// 静态资源处理器:带 ETag + Cache-Control
fs := http.FileServer(http.Dir("./static"))
mux.Handle("/static/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
w.Header().Set("Vary", "Accept-Encoding")
etag := `"` + r.URL.Path + `"`
w.Header().Set("ETag", etag)
if r.Header.Get("If-None-Match") == etag {
pushHit.WithLabelValues(r.URL.Path).Inc()
w.WriteHeader(http.StatusNotModified)
return
}
fs.ServeHTTP(w, r)
}))
// 同时监听 443(TLS)与 80(h2c 降级)
go func() {
srv := &http.Server{
Addr: ":80",
Handler: h2c.NewHandler(mux, &http2.Server{}),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}()
cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
if err != nil {
log.Fatalf("load cert: %v", err)
}
srv := &http.Server{
Addr: ":443",
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
NextProtos: []string{"h2", "http/1.1"},
},
Handler: mux,
}
log.Fatal(srv.ListenAndServeTLS("", ""))
}
运行效果:
- 首次访问
/,浏览器收到 PUSH_PROMISE,RTT 减少 1 次; - 刷新页面,静态资源返回 304,
push_hit_total递增,缓存命中率 ≈ 100 %; - 对比组加
?nopush=1,Prometheus 面板可实时看到命中率差异。
拓展思考
- 灰度策略:按用户 Cookie
ab=push决定是否 Push,结合阿里云 MSE 全链路灰度做渐进式放量。 - CDN 协同:边缘节点若已缓存,Push 会浪费带宽,可在源站回源时加
CDN-Loop头,检测到 CDN 命中则跳过 Push。 - QUIC/HTTP3:Go 1.21 实验包
golang.org/x/net/http3已支持,Server Push 在 HTTP/3 被官方废弃,需提前规划用 Early Hints (103) 替代,保持同样性能收益。