Skip to content

Commit 2e758ca

Browse files
committed
feat: 静态缓存
1 parent bec9c66 commit 2e758ca

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

internal/middleware/middleware.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,3 +223,43 @@ func extractAuthKey(c *gin.Context) string {
223223

224224
return ""
225225
}
226+
227+
// StaticCache creates a middleware for caching static resources
228+
func StaticCache() gin.HandlerFunc {
229+
return func(c *gin.Context) {
230+
path := c.Request.URL.Path
231+
232+
if isStaticResource(path) {
233+
c.Header("Cache-Control", "public, max-age=2592000, immutable")
234+
c.Header("Expires", time.Now().AddDate(1, 0, 0).UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT"))
235+
}
236+
237+
c.Next()
238+
}
239+
}
240+
241+
// isStaticResource 判断是否为静态资源
242+
func isStaticResource(path string) bool {
243+
staticPrefixes := []string{"/assets/"}
244+
staticSuffixes := []string{
245+
".js", ".css", ".ico", ".png", ".jpg", ".jpeg",
246+
".gif", ".svg", ".woff", ".woff2", ".ttf", ".eot",
247+
".webp", ".avif", ".map",
248+
}
249+
250+
// 检查路径前缀
251+
for _, prefix := range staticPrefixes {
252+
if strings.HasPrefix(path, prefix) {
253+
return true
254+
}
255+
}
256+
257+
// 检查文件扩展名
258+
for _, suffix := range staticSuffixes {
259+
if strings.HasSuffix(path, suffix) {
260+
return true
261+
}
262+
}
263+
264+
return false
265+
}

internal/router/router.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,13 +176,19 @@ func registerFrontendRoutes(router *gin.Engine, buildFS embed.FS, indexPage []by
176176
c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "Method not allowed"})
177177
})
178178

179+
// 使用静态资源缓存中间件
180+
router.Use(middleware.StaticCache())
181+
179182
router.Use(static.Serve("/", EmbedFolder(buildFS, "web/dist")))
180183
router.NoRoute(func(c *gin.Context) {
181184
if strings.HasPrefix(c.Request.RequestURI, "/api") || strings.HasPrefix(c.Request.RequestURI, "/proxy") {
182185
c.JSON(http.StatusNotFound, gin.H{"error": "Not Found"})
183186
return
184187
}
185-
c.Header("Cache-Control", "no-cache")
188+
// HTML页面不缓存,确保更新能及时生效
189+
c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
190+
c.Header("Pragma", "no-cache")
191+
c.Header("Expires", "0")
186192
c.Data(http.StatusOK, "text/html; charset=utf-8", indexPage)
187193
})
188194
}

0 commit comments

Comments
 (0)