perf: 静态文件完全绕过所有中间件
- 使用 gin.New() 替代 gin.Default(),避免默认中间件 - 添加 skipUploads 包装器,所有中间件跳过 /uploads/ 路径 - 静态文件路由注册在最前面,零中间件开销 - 移除 gzipMiddleware 中重复的跳过逻辑 Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
+21
-20
@@ -225,23 +225,19 @@ func startServer() {
|
|||||||
gin.SetMode(gin.ReleaseMode)
|
gin.SetMode(gin.ReleaseMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
r := gin.Default()
|
// 使用 gin.New() 而不是 gin.Default(),避免默认中间件
|
||||||
|
r := gin.New()
|
||||||
r.MaxMultipartMemory = 32 << 20
|
r.MaxMultipartMemory = 32 << 20
|
||||||
|
|
||||||
r.Use(middleware.Logger())
|
// 静态文件路由 - 注册在最前面,不经过任何中间件
|
||||||
r.Use(middleware.Recovery())
|
|
||||||
r.Use(middleware.Cors())
|
|
||||||
r.Use(gzipMiddleware())
|
|
||||||
|
|
||||||
r.Use(func(c *gin.Context) {
|
|
||||||
if strings.HasPrefix(c.Request.URL.Path, "/uploads/") {
|
|
||||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
})
|
|
||||||
|
|
||||||
// 优化的静态文件服务,支持 Range 请求和断点续传
|
|
||||||
r.GET("/uploads/*filepath", handleOptimizedStaticFile)
|
r.GET("/uploads/*filepath", handleOptimizedStaticFile)
|
||||||
|
|
||||||
|
// 以下中间件只对非 uploads 路径生效
|
||||||
|
r.Use(skipUploads(middleware.Logger()))
|
||||||
|
r.Use(skipUploads(middleware.Recovery()))
|
||||||
|
r.Use(skipUploads(middleware.Cors()))
|
||||||
|
r.Use(skipUploads(gzipMiddleware()))
|
||||||
|
|
||||||
router.SetupRoutes(r)
|
router.SetupRoutes(r)
|
||||||
setupEmbeddedFrontend(r)
|
setupEmbeddedFrontend(r)
|
||||||
|
|
||||||
@@ -258,6 +254,17 @@ func startServer() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// skipUploads 包装中间件,跳过 /uploads/ 路径
|
||||||
|
func skipUploads(handler gin.HandlerFunc) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
if strings.HasPrefix(c.Request.URL.Path, "/uploads/") {
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
handler(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func setupEmbeddedFrontend(r *gin.Engine) {
|
func setupEmbeddedFrontend(r *gin.Engine) {
|
||||||
distFS, err := fs.Sub(embeddedFiles, "embedded/dist")
|
distFS, err := fs.Sub(embeddedFiles, "embedded/dist")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -386,12 +393,6 @@ func isCompressibleContentType(contentType string) bool {
|
|||||||
|
|
||||||
func gzipMiddleware() gin.HandlerFunc {
|
func gzipMiddleware() gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
// 静态文件下载路径跳过 gzip 处理,避免影响下载性能
|
|
||||||
if strings.HasPrefix(c.Request.URL.Path, "/uploads/") {
|
|
||||||
c.Next()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") {
|
if !strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") {
|
||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user