fix: 修正微服务gin找不到templates的问题
This commit is contained in:
parent
5b7ec80473
commit
e8fcd550c1
@ -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"))
|
||||
})
|
||||
|
||||
// 路由设置
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user