Skip to content

Commit e590675

Browse files
committed
fix(路由): 修复前端单页应用路由404问题
- 修改 embed.FS 指令以正确包含前端静态资源 - 在 NoRoute 处理中区分静态资源、API 请求和前端路由 - 对于前端路由请求,直接返回内存中的 index.html 内容 - 更新前端构建生成的资源文件名
1 parent 53795f9 commit e590675

File tree

3 files changed

+27
-4
lines changed

3 files changed

+27
-4
lines changed

gotribe-admin.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ import (
4545
"github.com/fatih/color"
4646
)
4747

48-
//go:embed web/admin/dist/*
48+
//go:embed all:web/admin/dist
4949
var content embed.FS
5050

5151
func main() {

internal/app/routes/routes.go

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"gotribe-admin/internal/pkg/common"
1313
"gotribe-admin/internal/pkg/middleware"
1414
"net/http"
15+
"strings"
1516
"time"
1617

1718
jwt "github.com/appleboy/gin-jwt/v2"
@@ -90,10 +91,32 @@ func setupStaticFiles(r *gin.Engine, fs embed.FS) {
9091
return
9192
}
9293

94+
// 1. 尝试从 embed.FS 中读取 index.html 内容
95+
// 注意:这里需要使用完整的嵌入路径
96+
indexData, err := fs.ReadFile("web/admin/dist/index.html")
97+
if err != nil {
98+
common.Log.Errorf("读取 index.html 失败:%v", err)
99+
}
100+
101+
// 2. 静态资源服务 (处理 /assets, /favicon.ico 等)
93102
r.Use(static.Serve("/", embedFS))
103+
104+
// 3. SPA 兜底处理
94105
r.NoRoute(func(c *gin.Context) {
95-
common.Log.Infof("A 404 error occurred, but the specific URL path is not logged to prevent log injection.")
96-
c.Redirect(http.StatusMovedPermanently, "/")
106+
path := c.Request.URL.Path
107+
// 如果是静态资源请求(以/assets/开头)或API请求,返回404
108+
if strings.HasPrefix(path, "/assets/") || strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/swagger/") {
109+
c.AbortWithStatus(http.StatusNotFound)
110+
return
111+
}
112+
113+
// 对于前端路由,直接返回内存中的 index.html 内容
114+
if len(indexData) > 0 {
115+
c.Header("Content-Type", "text/html; charset=utf-8")
116+
c.String(http.StatusOK, string(indexData))
117+
} else {
118+
c.String(http.StatusNotFound, "Index file not found")
119+
}
97120
})
98121
}
99122

web/admin/dist/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Manrope:wght@200..800&display=swap"
1414
rel="stylesheet"
1515
/>
16-
<script type="module" crossorigin src="/assets/index-BDEUfSoP.js"></script>
16+
<script type="module" crossorigin src="/assets/index-Dz7RJ6Rz.js"></script>
1717
<link rel="stylesheet" crossorigin href="/assets/index-vsRf-QNN.css">
1818
</head>
1919
<body>

0 commit comments

Comments
 (0)