From e8fcd550c1d53bd4d23052a18a667907b5af287b Mon Sep 17 00:00:00 2001 From: yarnom Date: Tue, 14 Oct 2025 11:48:32 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=E5=BE=AE=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1gin=E6=89=BE=E4=B8=8D=E5=88=B0templates=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/server/gin.go | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/internal/server/gin.go b/internal/server/gin.go index c1455c5..8a08850 100644 --- a/internal/server/gin.go +++ b/internal/server/gin.go @@ -5,6 +5,7 @@ import ( "log" "net/http" "os" + "path/filepath" "strconv" "time" "weatherstation/internal/config" @@ -22,27 +23,51 @@ func StartGinServer() error { // 创建Gin引擎 r := gin.Default() - // 加载HTML模板 - r.LoadHTMLGlob("templates/*") + // 解析资源路径,兼容在仓库根目录或 bin/ 目录启动 + tplGlob := filepath.Join("templates", "*") + if _, err := os.Stat("templates"); os.IsNotExist(err) { + if _, err2 := os.Stat("../templates"); err2 == nil { + tplGlob = filepath.Join("..", "templates", "*") + } + } + r.LoadHTMLGlob(tplGlob) - // 静态文件服务 - r.Static("/static", "./static") + staticDir := "./static" + if _, err := os.Stat(staticDir); os.IsNotExist(err) { + if _, err2 := os.Stat("../static"); err2 == nil { + staticDir = "../static" + } + } + r.Static("/static", staticDir) // 前端SPA(Angular)静态资源与路由回退 - // 构建产物目录:./core/frontend/dist/ui + // 构建产物目录:./core/frontend/dist/ui(兼容 ../core/frontend/dist/ui) r.GET("/ui/*filepath", func(c *gin.Context) { // 物理文件优先,否则回退到 index.html(支持前端路由) requested := c.Param("filepath") if requested == "" || requested == "/" { - c.File("./core/frontend/dist/ui/index.html") + base := "./core/frontend/dist/ui/index.html" + if _, err := os.Stat(base); os.IsNotExist(err) { + alt := "../core/frontend/dist/ui/index.html" + if _, err2 := os.Stat(alt); err2 == nil { + base = alt + } + } + c.File(base) return } - full := ".//core/frontend/dist/ui" + requested + baseDir := "./core/frontend/dist/ui" + if _, err := os.Stat(baseDir); os.IsNotExist(err) { + if _, err2 := os.Stat("../core/frontend/dist/ui"); err2 == nil { + baseDir = "../core/frontend/dist/ui" + } + } + full := baseDir + requested if _, err := os.Stat(full); err == nil { c.File(full) return } - c.File("./core/frontend/dist/ui/index.html") + c.File(filepath.Join(baseDir, "index.html")) }) // 路由设置