This commit is contained in:
truewhile
2026-09-03 16:53:12 +08:00
parent 4150d03852
commit c702a68cfb
24 changed files with 691 additions and 168 deletions
+47
View File
@@ -0,0 +1,47 @@
package middleware
import (
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)
// gzipExcludedExtensions 已经是压缩格式(图片/字体/媒体/归档)的响应体,
// 再 gzip 只浪费 CPU 不省流量。
var gzipExcludedExtensions = []string{
".png", ".gif", ".jpeg", ".jpg", ".webp", ".avif", ".ico", ".svg",
".woff", ".woff2", ".ttf", ".otf",
".mp4", ".mkv", ".webm", ".ts", ".m4s", ".m3u8",
".mp3", ".flac", ".aac", ".ogg",
".zip", ".gz", ".xz", ".7z", ".rar",
}
// apiGzipExcludedPrefixes 大文件流式传输(Range 语义)与 WS/SSE 长连接
// 不参与 gzip:压缩会破坏 Range / 逐块推送语义。
var apiGzipExcludedPrefixes = []string{
"/api/stream/",
"/api/hls/",
"/api/img",
"/api/subtitles/",
"/api/strm/play/",
"/api/ws",
"/api/events",
}
// GzipAPI 压缩 /api 下的 JSON 响应(媒体列表动辄数 MB,压缩率 85%+)。
// gin-contrib/gzip 的路径排除是前缀匹配,且会自动校验 Accept-Encoding
// 与 Connection: Upgrade(WebSocket 安全)。
func GzipAPI() gin.HandlerFunc {
return gzip.Gzip(
gzip.DefaultCompression,
gzip.WithExcludedExtensions(gzipExcludedExtensions),
gzip.WithExcludedPaths(apiGzipExcludedPrefixes),
)
}
// GzipStatic 压缩 SPA 静态资源(JS/CSS/HTML 是构建产物的大头)。
func GzipStatic() gin.HandlerFunc {
return gzip.Gzip(
gzip.DefaultCompression,
gzip.WithExcludedExtensions(gzipExcludedExtensions),
)
}
+84
View File
@@ -0,0 +1,84 @@
package middleware
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func newGzipTestRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
api := router.Group("/api")
api.Use(GzipAPI())
api.GET("/libraries", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"items": strings.Repeat("mebox", 200)})
})
api.GET("/stream/:id", func(c *gin.Context) {
c.String(http.StatusOK, strings.Repeat("video-bytes", 200))
})
router.GET("/assets/app.js", GzipStatic(), func(c *gin.Context) {
c.Data(http.StatusOK, "text/javascript", []byte(strings.Repeat("console.log(1);", 200)))
})
return router
}
func TestGzipAPICompressesJSONWhenAccepted(t *testing.T) {
router := newGzipTestRouter()
req := httptest.NewRequest(http.MethodGet, "/api/libraries", nil)
req.Header.Set("Accept-Encoding", "gzip")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if got := w.Header().Get("Content-Encoding"); got != "gzip" {
t.Fatalf("Content-Encoding = %q, want gzip", got)
}
if raw := strings.Repeat("mebox", 200); w.Body.Len() >= len(raw) {
t.Fatalf("body not compressed: len = %d, raw = %d", w.Body.Len(), len(raw))
}
}
func TestGzipAPISkipsWhenNotAccepted(t *testing.T) {
router := newGzipTestRouter()
req := httptest.NewRequest(http.MethodGet, "/api/libraries", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if got := w.Header().Get("Content-Encoding"); got == "gzip" {
t.Fatal("Content-Encoding should not be gzip without Accept-Encoding")
}
}
func TestGzipAPIExcludesStreamPath(t *testing.T) {
router := newGzipTestRouter()
req := httptest.NewRequest(http.MethodGet, "/api/stream/abc", nil)
req.Header.Set("Accept-Encoding", "gzip")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if got := w.Header().Get("Content-Encoding"); got == "gzip" {
t.Fatal("stream path must not be gzipped (Range semantics)")
}
}
func TestGzipStaticCompressesAssets(t *testing.T) {
router := newGzipTestRouter()
req := httptest.NewRequest(http.MethodGet, "/assets/app.js", nil)
req.Header.Set("Accept-Encoding", "gzip")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if got := w.Header().Get("Content-Encoding"); got != "gzip" {
t.Fatalf("Content-Encoding = %q, want gzip for static assets", got)
}
}