进阶 www.iris-go.com 2026-10-20 02:39:14 · 18 阅读

第48章 HTTP/2 Server Push

HTTP/2 Server Push 学习如何在 Iris 中实现 HTTP/2 Server Push。 Basic Server Push ```go package main import "github.com/kataras/iris/v12" func main() { app := iris.New() app.Get("/", func(ctx iris.Context) { if pusher := ctx.ResponseWriter().Pusher(); pusher != nil { // Push CSS file if err := pusher.Push("/assets/style.css", nil); err != nil { ctx.Application().Logger().Warnf("Failed to push: %v", err) } // Push JavaScript file if err := pusher.Push("/assets/app.js", nil); err != nil { ctx.Application().Logger().Warnf("Failed to push: %v", err) } } ctx.View("index.html") }) app.Listen(":8080", iris.WithOptimizations) } ``` 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Advanced Push Options ```go app.Get("/", func(ctx iris.Context) { if pusher := ctx.ResponseWriter().Pusher(); pusher != nil { opts := &http.PushOptions{ Header: http.Header{ "Accept-Encoding": ctx.Request().Header["Accept-Encoding"], }, Method: "GET", } assets := []string{ "/assets/css/style.css", "/assets/js/app.js", "/assets/images/logo.png", } for _, asset := range assets { if err := pusher.Push(asset, opts); err != nil { ctx.Application().Logger().Warnf("Failed to push %s: %v", asset, err) } } } ctx.View("index.html") }) ``` 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
条件式推送 在以下代码片段中,我们使用条件判断来控制 Server Push 的行为。首先检查客户端是否支持 HTTP/2,随后通过响应头的 `Pusher` 接口来推送资源。核心策略是优先推送关键资源,并在单独的 goroutine 中推送非关键资源,以避免阻塞请求处理: ```go goapp.Get("/", func(ctx iris.Context) { // 若客户端不支持 HTTP/2,则直接返回视图 if !ctx.ClientSupportsHTTP2() { ctx.View("index.html") return } // 获取 Pusher 接口 if pusher := ctx.ResponseWriter().Pusher(); pusher != nil { // 1. 优先推送关键资源 criticalAssets := []string{ "/assets/css/critical.css", "/assets/js/critical.js", } for _, asset := range criticalAssets { if err := pusher.Push(asset, nil); err != nil { ctx.Application().Logger().Warnf("推送失败 %s: %v", asset, err) } } // 2. 在独立协程中推送非关键资源 go func() { nonCriticalAssets := []string{ "/assets/css/non-critical.css", "/assets/js/non-critical.js", } for _, asset := range nonCriticalAssets { if err := pusher.Push(asset, nil); err != nil { ctx.Application().Logger().Warnf("推送失败 %s: %v", asset, err) } } }() } ctx.View("index.html") }) ``` 在实现 Server Push 时,建议遵循以下最佳实践,以平衡性能与复杂度: * 实现策略: * 优先推送关键资源(Critical Resources)。 * 检测客户端的协议支持情况。 * 妥善处理推送过程中的错误。 * 监控推送请求的生效状态。 * 及时清理不再需要的资源引用。 * 性能优化: * 选择性推送,避免盲目加载所有资源。 * 明确资源优先级,确保关键路径优先。 * 监控推送对总体性能(如 TTFB、TTI)的影响。 * 设置合适的超时机制。 * 定期清理资源缓存。 * 头部管理: * 设置标准的 `Link` 或 `Push-Policy` 头。 * 正确处理内容编码(Content-Encoding)。 * 配置合适的缓存策略。 * 监控特定头部的支持度。 * 处理由头部引发的潜在错误。 * 运维维护: * 监控 Server Push 的实际使用情况。 * 随着代码库演进,同步更新推送的资源列表。 * 定期进行回归测试。 * 文档化相关的配置变更。 * 持续审查并调整性能指标。

评论 (0)