fix: 修复http.FS过滤下划线开头文件导致404的问题
- 使用fs.ReadFile直接读取文件内容替代c.FileFromFS - http.FileServer/http.FS默认过滤以_开头的文件 - 手动设置Content-Type确保正确的MIME类型 - 移除不再需要的net/http导入
This commit is contained in:
+42
-7
@@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -283,16 +282,40 @@ func setupEmbeddedFrontend(r *gin.Engine) {
|
||||
|
||||
fullPath := "assets/" + decodedPath
|
||||
|
||||
f, err := distFS.Open(fullPath)
|
||||
data, err := fs.ReadFile(distFS, fullPath)
|
||||
if err != nil {
|
||||
log.Printf("[Assets] File not found in embedded FS: %s, error: %v", fullPath, err)
|
||||
c.Status(404)
|
||||
return
|
||||
}
|
||||
f.Close()
|
||||
|
||||
contentType := "application/octet-stream"
|
||||
switch {
|
||||
case strings.HasSuffix(decodedPath, ".js"):
|
||||
contentType = "application/javascript"
|
||||
case strings.HasSuffix(decodedPath, ".css"):
|
||||
contentType = "text/css"
|
||||
case strings.HasSuffix(decodedPath, ".html"):
|
||||
contentType = "text/html"
|
||||
case strings.HasSuffix(decodedPath, ".json"):
|
||||
contentType = "application/json"
|
||||
case strings.HasSuffix(decodedPath, ".png"):
|
||||
contentType = "image/png"
|
||||
case strings.HasSuffix(decodedPath, ".jpg") || strings.HasSuffix(decodedPath, ".jpeg"):
|
||||
contentType = "image/jpeg"
|
||||
case strings.HasSuffix(decodedPath, ".svg"):
|
||||
contentType = "image/svg+xml"
|
||||
case strings.HasSuffix(decodedPath, ".ico"):
|
||||
contentType = "image/x-icon"
|
||||
case strings.HasSuffix(decodedPath, ".woff"):
|
||||
contentType = "font/woff"
|
||||
case strings.HasSuffix(decodedPath, ".woff2"):
|
||||
contentType = "font/woff2"
|
||||
}
|
||||
|
||||
c.Header("Content-Type", contentType)
|
||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
c.FileFromFS(fullPath, http.FS(distFS))
|
||||
c.Data(200, contentType, data)
|
||||
})
|
||||
|
||||
r.NoRoute(func(c *gin.Context) {
|
||||
@@ -306,9 +329,21 @@ func setupEmbeddedFrontend(r *gin.Engine) {
|
||||
if err != nil {
|
||||
decodedPath = path
|
||||
}
|
||||
if f, err := distFS.Open(decodedPath); err == nil {
|
||||
f.Close()
|
||||
c.FileFromFS(c.Request.URL.Path, http.FS(distFS))
|
||||
if data, err := fs.ReadFile(distFS, decodedPath); err == nil {
|
||||
contentType := "application/octet-stream"
|
||||
switch {
|
||||
case strings.HasSuffix(decodedPath, ".js"):
|
||||
contentType = "application/javascript"
|
||||
case strings.HasSuffix(decodedPath, ".css"):
|
||||
contentType = "text/css"
|
||||
case strings.HasSuffix(decodedPath, ".html"):
|
||||
contentType = "text/html"
|
||||
case strings.HasSuffix(decodedPath, ".png"):
|
||||
contentType = "image/png"
|
||||
case strings.HasSuffix(decodedPath, ".svg"):
|
||||
contentType = "image/svg+xml"
|
||||
}
|
||||
c.Data(200, contentType, data)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user