From 2e758caadaf9b48e563e30b1f337a507285abe84 Mon Sep 17 00:00:00 2001 From: tbphp Date: Wed, 23 Jul 2025 23:02:40 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=9D=99=E6=80=81=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/middleware/middleware.go | 40 +++++++++++++++++++++++++++++++ internal/router/router.go | 8 ++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/internal/middleware/middleware.go b/internal/middleware/middleware.go index 91b77fd..a1f10dc 100644 --- a/internal/middleware/middleware.go +++ b/internal/middleware/middleware.go @@ -223,3 +223,43 @@ func extractAuthKey(c *gin.Context) string { return "" } + +// StaticCache creates a middleware for caching static resources +func StaticCache() gin.HandlerFunc { + return func(c *gin.Context) { + path := c.Request.URL.Path + + if isStaticResource(path) { + c.Header("Cache-Control", "public, max-age=2592000, immutable") + c.Header("Expires", time.Now().AddDate(1, 0, 0).UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT")) + } + + c.Next() + } +} + +// isStaticResource 判断是否为静态资源 +func isStaticResource(path string) bool { + staticPrefixes := []string{"/assets/"} + staticSuffixes := []string{ + ".js", ".css", ".ico", ".png", ".jpg", ".jpeg", + ".gif", ".svg", ".woff", ".woff2", ".ttf", ".eot", + ".webp", ".avif", ".map", + } + + // 检查路径前缀 + for _, prefix := range staticPrefixes { + if strings.HasPrefix(path, prefix) { + return true + } + } + + // 检查文件扩展名 + for _, suffix := range staticSuffixes { + if strings.HasSuffix(path, suffix) { + return true + } + } + + return false +} diff --git a/internal/router/router.go b/internal/router/router.go index 85ef37a..f5703ec 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -176,13 +176,19 @@ func registerFrontendRoutes(router *gin.Engine, buildFS embed.FS, indexPage []by c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "Method not allowed"}) }) + // 使用静态资源缓存中间件 + router.Use(middleware.StaticCache()) + router.Use(static.Serve("/", EmbedFolder(buildFS, "web/dist"))) router.NoRoute(func(c *gin.Context) { if strings.HasPrefix(c.Request.RequestURI, "/api") || strings.HasPrefix(c.Request.RequestURI, "/proxy") { c.JSON(http.StatusNotFound, gin.H{"error": "Not Found"}) return } - c.Header("Cache-Control", "no-cache") + // HTML页面不缓存,确保更新能及时生效 + c.Header("Cache-Control", "no-cache, no-store, must-revalidate") + c.Header("Pragma", "no-cache") + c.Header("Expires", "0") c.Data(http.StatusOK, "text/html; charset=utf-8", indexPage) }) }