This commit is contained in:
truewhile
2026-10-29 00:09:00 +08:00
parent 416d4c8c3b
commit db516ded61
11 changed files with 1397 additions and 19 deletions
+12
View File
@@ -17,12 +17,24 @@ var gzipExcludedExtensions = []string{
// apiGzipExcludedPrefixes 大文件流式传输(Range 语义)与 WS/SSE 长连接
// 不参与 gzip:压缩会破坏 Range / 逐块推送语义。
//
// 阅读媒体代理(/api/reader/media、/api/reader/local/audio、
// /api/reader/audio/transcode)同样必须排除,原因有两条:
// - 它们透传上游的 206 Partial Content。gin-contrib/gzip 在压缩时会删掉
// Content-Length,却把 Content-Range 原样留下,客户端看到的是「声明
// N 字节、实际收到 M 字节的 gzip 流」,自己发 Accept-Encoding 的播放器
// (ExoPlayer 不透明处理)直接判 ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED。
// - 音视频本来就是压缩格式,再 gzip 一遍只烧 CPU(3.5MB 的 m4a 压完还是
// 3.5MB 量级),对带宽没有收益。
var apiGzipExcludedPrefixes = []string{
"/api/stream/",
"/api/hls/",
"/api/img",
"/api/subtitles/",
"/api/strm/play/",
"/api/reader/media",
"/api/reader/local/audio",
"/api/reader/audio/transcode",
"/api/ws",
"/api/events",
}
+46
View File
@@ -70,6 +70,52 @@ func TestGzipAPIExcludesStreamPath(t *testing.T) {
}
}
// TestGzipAPIExcludesReaderMedia 阅读媒体代理必须排除在 gzip 之外。
//
// 它会透传 CDN 的 206 Partial Content。gin-contrib/gzip 压缩时会删掉
// Content-Length 却保留 Content-Range,客户端看到「声明 N 字节、实收 M 字节」,
// 自己发 Accept-Encoding 的播放器(ExoPlayer)直接判
// ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED,表现为「音频格式不支持」。
func TestGzipAPIExcludesReaderMedia(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
api := router.Group("/api")
api.Use(GzipAPI())
// 用 206 + Content-Range 模拟真实的音频分段响应。
segment := func(c *gin.Context) {
c.Header("Content-Range", "bytes 0-99/100")
c.Data(http.StatusPartialContent, "audio/mp4", []byte(strings.Repeat("x", 4096)))
}
for _, path := range []string{
"/reader/media",
"/reader/local/audio",
"/reader/audio/transcode",
} {
api.GET(path, segment)
}
for _, path := range []string{
"/reader/media",
"/reader/local/audio",
"/reader/audio/transcode",
} {
req := httptest.NewRequest(http.MethodGet, "/api"+path+"?b=book&u=x&s=y", nil)
req.Header.Set("Accept-Encoding", "gzip")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if got := w.Header().Get("Content-Encoding"); got == "gzip" {
t.Errorf("%s 不该被 gzip(Range 语义会被破坏)", path)
}
if got := w.Header().Get("Content-Range"); got != "bytes 0-99/100" {
t.Errorf("%s 的 Content-Range 被破坏: %q", path, got)
}
if w.Body.Len() != 4096 {
t.Errorf("%s 响应体长度 = %d,期望 4096", path, w.Body.Len())
}
}
}
func TestGzipStaticCompressesAssets(t *testing.T) {
router := newGzipTestRouter()