perf: 添加gzip压缩提升前端资源加载速度

- 对JS/CSS/HTML/JSON/SVG等文本资源启用gzip压缩
- 传输体积可减少70-80%,大幅提升页面加载速度
- 图片和字体等已压缩格式不重复压缩
This commit is contained in:
2026-05-05 12:15:46 +08:00
parent bb802e765c
commit bc30afe106
2 changed files with 113 additions and 86 deletions
+23 -2
View File
@@ -1,6 +1,7 @@
package main
import (
"compress/gzip"
"embed"
"fmt"
"io/fs"
@@ -273,9 +274,19 @@ func setupEmbeddedFrontend(r *gin.Engine) {
}
contentType := getContentType(decodedPath)
c.Header("Cache-Control", "public, max-age=31536000, immutable")
c.Data(200, contentType, data)
if strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") && isCompressible(decodedPath) {
c.Header("Content-Encoding", "gzip")
c.Header("Vary", "Accept-Encoding")
c.Writer.WriteHeader(200)
c.Writer.Header().Set("Content-Type", contentType)
gw := gzip.NewWriter(c.Writer)
gw.Write(data)
gw.Close()
} else {
c.Data(200, contentType, data)
}
})
r.NoRoute(func(c *gin.Context) {
@@ -334,6 +345,16 @@ func getSettingString(settings map[string]interface{}, key, defaultValue string)
return defaultValue
}
func isCompressible(filename string) bool {
ext := strings.ToLower(filename[strings.LastIndex(filename, "."):])
switch ext {
case ".js", ".mjs", ".css", ".html", ".json", ".svg", ".xml", ".txt":
return true
default:
return false
}
}
func getContentType(filename string) string {
ext := strings.ToLower(filename[strings.LastIndex(filename, "."):])
switch ext {