feat: 更新嵌入式文件系统逻辑,支持路径清理和静态资源请求处理,增强前端主题切换能力

This commit is contained in:
ryan
2026-03-11 13:18:32 +08:00
parent 6eea676f8f
commit ad090c9c04
26 changed files with 465 additions and 81 deletions
+43
View File
@@ -7,16 +7,59 @@ import (
"embed"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"io/fs"
"net/http"
pathpkg "path"
"strings"
)
func setWebRouter(router *gin.Engine, buildFS embed.FS, indexPage []byte) {
exportedBuildFS, err := fs.Sub(buildFS, "web/build")
if err != nil {
panic(err)
}
router.Use(middleware.GlobalWebRateLimit())
fileDownloadRoute := router.Group("/")
fileDownloadRoute.GET("/upload/:file", middleware.DownloadRateLimit(), controller.DownloadFile)
router.Use(middleware.Cache())
router.Use(static.Serve("/", common.EmbedFolder(buildFS, "web/build")))
router.NoRoute(func(c *gin.Context) {
if serveExportedPage(c, exportedBuildFS) {
return
}
if isStaticAssetRequest(c.Request.URL.Path) {
c.Status(http.StatusNotFound)
return
}
c.Data(http.StatusOK, "text/html; charset=utf-8", indexPage)
})
}
func serveExportedPage(c *gin.Context, buildFS fs.FS) bool {
requestPath := strings.Trim(c.Request.URL.Path, "/")
candidates := []string{"index.html"}
if requestPath != "" {
candidates = []string{
requestPath + ".html",
pathpkg.Join(requestPath, "index.html"),
}
}
for _, candidate := range candidates {
content, err := fs.ReadFile(buildFS, candidate)
if err == nil {
c.Data(http.StatusOK, "text/html; charset=utf-8", content)
return true
}
}
return false
}
func isStaticAssetRequest(requestPath string) bool {
return strings.HasPrefix(requestPath, "/_next/") || pathpkg.Ext(requestPath) != ""
}