前端: - src/srv/api → src/api,按域分文件夹(auth/cluster/host/storage/deployment/collector) - 新增 http.ts 引擎(http.get/post/put/delete),域模块改用语义化调用 - index.html 增加 favicon(匹配应用 logo 的 emerald + Activity 脉冲) 后端分层增强(保留包名): - 新增 repository/:从 models 拆出 JsonDB 持久化层(InitDB/GetDB/Shutdown/RequestSave) - 新增 dto/:从 controllers 抽出各域请求契约(带 binding 校验) - 新增 pkg/crypto、pkg/jwt:从 utils 拆出安全原语(外部 jwt 别名 jwtv5 避免冲突) - models 只留领域实体 + sanitizer;utils 只留 gin/应用相关(response/errors) v2 优化移植与缺陷修复: - 移植密钥分离/SSH TOFU/并发写安全/Loki 生产级配置/Docker 加固 - 修复 deployment.go 并发丢更新、Helm values 重复键、EncryptField 哨兵、loki-gateway 端点等审计缺陷 - 实现真正的优雅关停(main.go http.Server + signal + repository.Shutdown) - 修复登录契约:后端返回 accessToken,前端 auth.ts/Login.tsx 对齐 - 补 crypto/jwt/repository 单元测试(含并发写回归) 验证: go build/vet/test 全绿;npm run build 通过;登录→鉴权→优雅关停冒烟通过 Co-Authored-By: Claude <noreply@anthropic.com>
172 lines
5.6 KiB
Go
172 lines
5.6 KiB
Go
package routers
|
||
|
||
import (
|
||
"net/http"
|
||
"os"
|
||
"path/filepath"
|
||
"strings"
|
||
"time"
|
||
|
||
"lokideploy/controllers"
|
||
"lokideploy/middleware"
|
||
|
||
"github.com/gin-contrib/cors"
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
func SetupRouter() *gin.Engine {
|
||
r := gin.Default()
|
||
|
||
// CORS
|
||
cfg := cors.DefaultConfig()
|
||
cfg.AllowAllOrigins = true
|
||
cfg.AllowHeaders = []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Requested-With"}
|
||
cfg.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"}
|
||
r.Use(cors.New(cfg))
|
||
|
||
// Controllers
|
||
authCtrl := controllers.NewAuthController()
|
||
clusterCtrl := controllers.NewClusterController()
|
||
hostCtrl := controllers.NewHostController()
|
||
storageCtrl := controllers.NewStorageController()
|
||
deploymentCtrl := controllers.NewDeploymentController()
|
||
collectorCtrl := controllers.NewCollectorController()
|
||
|
||
// API v1
|
||
api := r.Group("/api/v1")
|
||
|
||
// 健康检查(公开访问,用于负载均衡和监控)
|
||
api.GET("/health", func(c *gin.Context) {
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"status": "ok",
|
||
"timestamp": time.Now().Unix(),
|
||
"version": "2.0.0",
|
||
})
|
||
})
|
||
|
||
// Prometheus metrics 端点(公开访问,可被Prometheus抓取)
|
||
api.GET("/metrics", func(c *gin.Context) {
|
||
// 基础metrics输出(符合Prometheus文本格式)
|
||
c.Header("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
|
||
c.String(http.StatusOK, "# LokiDeploy Metrics\n")
|
||
})
|
||
|
||
// Public
|
||
api.POST("/auth/login", authCtrl.Login)
|
||
api.POST("/auth/refresh", authCtrl.RefreshToken)
|
||
|
||
// Auth required
|
||
authorized := api.Group("")
|
||
authorized.Use(middleware.JWTAuth())
|
||
|
||
// Auth routes
|
||
authorized.GET("/auth/user", authCtrl.GetUser)
|
||
authorized.POST("/auth/password", authCtrl.ChangePassword)
|
||
authorized.POST("/auth/register", middleware.AdminAuth(), authCtrl.Register)
|
||
|
||
// Clusters
|
||
authorized.GET("/clusters", clusterCtrl.List)
|
||
authorized.GET("/clusters/:id", clusterCtrl.Get)
|
||
authorized.POST("/clusters", clusterCtrl.Create)
|
||
authorized.PUT("/clusters/:id", clusterCtrl.Update)
|
||
authorized.DELETE("/clusters/:id", clusterCtrl.Delete)
|
||
authorized.POST("/clusters/:id/validate", clusterCtrl.Validate)
|
||
authorized.GET("/clusters/:id/info", clusterCtrl.GetInfo)
|
||
|
||
// Hosts
|
||
authorized.GET("/hosts", hostCtrl.List)
|
||
authorized.GET("/hosts/:id", hostCtrl.Get)
|
||
authorized.POST("/hosts", hostCtrl.Create)
|
||
authorized.PUT("/hosts/:id", hostCtrl.Update)
|
||
authorized.DELETE("/hosts/:id", hostCtrl.Delete)
|
||
authorized.POST("/hosts/:id/validate", hostCtrl.Validate)
|
||
authorized.GET("/hosts/:id/info", hostCtrl.GetInfo)
|
||
authorized.POST("/hosts/:id/execute", hostCtrl.Execute)
|
||
|
||
// Storage
|
||
authorized.GET("/storages", storageCtrl.List)
|
||
authorized.GET("/storages/:id", storageCtrl.Get)
|
||
authorized.POST("/storages", storageCtrl.Create)
|
||
authorized.PUT("/storages/:id", storageCtrl.Update)
|
||
authorized.DELETE("/storages/:id", storageCtrl.Delete)
|
||
authorized.GET("/storages/default", storageCtrl.GetDefault)
|
||
|
||
// Deployments
|
||
authorized.GET("/deployments", deploymentCtrl.List)
|
||
authorized.GET("/deployments/:id", deploymentCtrl.Get)
|
||
authorized.POST("/deployments", deploymentCtrl.Create)
|
||
authorized.PUT("/deployments/:id", deploymentCtrl.Update)
|
||
authorized.DELETE("/deployments/:id", deploymentCtrl.Delete)
|
||
authorized.POST("/deployments/:id/deploy", deploymentCtrl.Deploy)
|
||
authorized.POST("/deployments/:id/stop", deploymentCtrl.Stop)
|
||
authorized.POST("/deployments/:id/restart", deploymentCtrl.Restart)
|
||
authorized.GET("/deployments/:id/logs", deploymentCtrl.GetLogs)
|
||
authorized.GET("/deployments/stats", deploymentCtrl.GetStats)
|
||
|
||
// Collectors
|
||
authorized.GET("/collectors", collectorCtrl.List)
|
||
authorized.GET("/collectors/:id", collectorCtrl.Get)
|
||
authorized.POST("/collectors", collectorCtrl.Create)
|
||
authorized.PUT("/collectors/:id", collectorCtrl.Update)
|
||
authorized.DELETE("/collectors/:id", collectorCtrl.Delete)
|
||
authorized.POST("/collectors/:id/install", collectorCtrl.Install)
|
||
authorized.POST("/collectors/:id/uninstall", collectorCtrl.Uninstall)
|
||
|
||
// Static files - use executable directory as base
|
||
distPath := findDistPath()
|
||
|
||
if distPath != "" {
|
||
r.Static("/assets", filepath.Join(distPath, "assets"))
|
||
|
||
// favicon:NoRoute 会把所有非 /api/ 请求回退到 index.html,
|
||
// 故此处显式注册 /favicon.svg 与 /favicon.ico,否则浏览器请求图标只会拿到 HTML。
|
||
faviconSVG := filepath.Join(distPath, "favicon.svg")
|
||
serveFavicon := func(c *gin.Context) {
|
||
if _, err := os.Stat(faviconSVG); err != nil {
|
||
c.Status(404)
|
||
return
|
||
}
|
||
c.Header("Content-Type", "image/svg+xml")
|
||
c.File(faviconSVG)
|
||
}
|
||
r.GET("/favicon.svg", serveFavicon)
|
||
r.GET("/favicon.ico", serveFavicon)
|
||
|
||
r.NoRoute(func(c *gin.Context) {
|
||
if strings.HasPrefix(c.Request.URL.Path, "/api/") {
|
||
c.JSON(404, gin.H{"code": 404, "message": "API endpoint not found"})
|
||
return
|
||
}
|
||
c.File(filepath.Join(distPath, "index.html"))
|
||
})
|
||
}
|
||
|
||
return r
|
||
}
|
||
|
||
// findDistPath finds the frontend dist directory
|
||
func findDistPath() string {
|
||
// Try relative to executable
|
||
if ex, err := os.Executable(); err == nil {
|
||
execDir := filepath.Dir(ex)
|
||
// If running via "go run", executable is in temp dir - fall through
|
||
if !strings.Contains(execDir, "/tmp/go-build") {
|
||
for _, rel := range []string{"dist", "../dist", "../../dist"} {
|
||
p := filepath.Join(execDir, rel)
|
||
if _, err := os.Stat(filepath.Join(p, "index.html")); err == nil {
|
||
return p
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// Try working directory relative paths
|
||
for _, p := range []string{"./dist", "../dist", "/app/dist"} {
|
||
if abs, err := filepath.Abs(p); err == nil {
|
||
if _, err := os.Stat(filepath.Join(abs, "index.html")); err == nil {
|
||
return abs
|
||
}
|
||
}
|
||
}
|
||
return ""
|
||
}
|