-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
202 lines (178 loc) · 6.1 KB
/
Copy pathmain.go
File metadata and controls
202 lines (178 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"context"
"embed"
"errors"
"flag"
"io/fs"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os/signal"
"strings"
"syscall"
"time"
"code-bench/database"
"code-bench/handlers"
"code-bench/models"
"github.com/gin-gonic/gin"
)
//go:embed all:frontend/dist
var frontendFS embed.FS
func main() {
configPath := flag.String("config", "config.yaml", "Path to config file")
flag.Parse()
// 1. Load configuration
if err := models.LoadConfig(*configPath); err != nil {
log.Fatalf("Failed to load config: %v", err)
}
// 2. Initialize Database
database.InitDB()
// 3. Initialize Gin engine
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
if models.AppConfig.Server.GinLog {
r.Use(gin.Logger())
}
// 4. Setup embed FS for frontend
distFS, distErr := fs.Sub(frontendFS, "frontend/dist")
if distErr != nil {
log.Println("Warning: frontend dist folder not found, skipping frontend embedding.")
}
// 5. Setup built-in dynamic reverse proxies for sub microservices
for prefix, targetURL := range models.AppConfig.Gateways {
target, err := url.Parse(targetURL)
if err != nil {
log.Fatalf("Invalid target URL for prefix %s: %v", prefix, err)
}
proxy := httputil.NewSingleHostReverseProxy(target)
p := prefix // local copy for closure
r.Any("/"+p+"/*path", func(c *gin.Context) {
path := c.Request.URL.Path
// Only proxy API requests, static assets, or module federation entry files
if strings.HasPrefix(path, "/"+p+"/api") ||
strings.HasPrefix(path, "/"+p+"/assets") ||
strings.HasSuffix(path, "remoteEntry.js") {
if models.AppConfig.Server.GinLog {
log.Printf("[Proxy] Forwarding request %s %s to %s", c.Request.Method, path, p)
}
proxy.ServeHTTP(c.Writer, c.Request)
} else {
// Serve the portal's index.html to allow portal's frontend routing & unified authentication
if distErr == nil {
indexBytes, err := fs.ReadFile(distFS, "index.html")
if err == nil {
c.Data(http.StatusOK, "text/html; charset=utf-8", indexBytes)
return
}
}
c.JSON(http.StatusNotFound, gin.H{"error": "Resource not found"})
}
})
}
// 6. Register Core APIs (Unprotected)
api := r.Group("/api")
{
api.POST("/login", handlers.Login)
api.GET("/auth/config", handlers.GetAuthConfig)
api.GET("/oauth2/authorize", handlers.StartOAuth2Flow)
api.GET("/oauth2/callback", handlers.OAuth2Callback)
}
// Protected Core APIs
apiProtected := r.Group("/api")
apiProtected.Use(handlers.AuthMiddleware())
{
apiProtected.GET("/me", handlers.GetMe)
apiProtected.PATCH("/password", handlers.UpdatePassword)
apiProtected.POST("/me/department", handlers.UpdateMyDepartment)
apiProtected.GET("/me/department-proxy", handlers.GetMyDepartmentProxy)
// Department APIs
apiProtected.GET("/departments", handlers.GetDepartments)
apiProtected.POST("/departments", handlers.CreateDepartment)
apiProtected.PATCH("/departments/:id", handlers.UpdateDepartment)
apiProtected.DELETE("/departments/:id", handlers.DeleteDepartment)
apiProtected.POST("/departments/import", handlers.ImportDepartments)
apiProtected.GET("/departments/export", handlers.ExportDepartments)
// User APIs (Admin only)
adminUsers := apiProtected.Group("/users")
adminUsers.Use(handlers.AdminMiddleware())
{
adminUsers.GET("", handlers.GetUsers)
adminUsers.POST("", handlers.CreateUser)
adminUsers.PUT("/:id", handlers.UpdateUser)
adminUsers.PATCH("/:id/status", handlers.UpdateUserStatus)
adminUsers.DELETE("/:id", handlers.DeleteUser)
adminUsers.POST("/import", handlers.ImportUsers)
adminUsers.GET("/export", handlers.ExportUsers)
}
// Repository APIs
apiProtected.GET("/repos", handlers.GetRepos)
apiProtected.POST("/repos", handlers.CreateRepo)
apiProtected.PATCH("/repos/:id", handlers.UpdateRepo)
apiProtected.DELETE("/repos/:id", handlers.DeleteRepo)
apiProtected.POST("/repos/import", handlers.ImportRepos)
apiProtected.GET("/repos/export", handlers.ExportRepos)
// Architecture Element APIs
apiProtected.GET("/arch-elements", handlers.GetArchElements)
apiProtected.POST("/arch-elements", handlers.CreateArchElement)
apiProtected.PATCH("/arch-elements/:id", handlers.UpdateArchElement)
apiProtected.DELETE("/arch-elements/:id", handlers.DeleteArchElement)
}
// 7. Serve frontend static files
if distErr == nil {
httpFS := http.FS(distFS)
r.NoRoute(func(c *gin.Context) {
path := c.Request.URL.Path
// DO NOT serve frontend index.html for API routes
if len(path) >= 4 && path[:4] == "/api" {
c.JSON(http.StatusNotFound, gin.H{"error": "API route not found"})
return
}
// Strip leading slash to look up in embedded FS
cleanPath := path
if cleanPath != "" && cleanPath != "/" {
f, err := distFS.Open(cleanPath[1:])
if err == nil {
f.Close()
c.FileFromFS(cleanPath, httpFS)
return
}
}
indexBytes, err := fs.ReadFile(distFS, "index.html")
if err != nil {
c.String(http.StatusNotFound, "index.html not found")
return
}
c.Data(http.StatusOK, "text/html; charset=utf-8", indexBytes)
})
}
// 7. Start HTTP Server
port := models.AppConfig.Server.Port
srv := &http.Server{
Addr: port,
Handler: r,
ReadTimeout: models.AppConfig.Server.ReadTimeout,
ReadHeaderTimeout: models.AppConfig.Server.ReadHeaderTimeout,
WriteTimeout: models.AppConfig.Server.WriteTimeout,
IdleTimeout: models.AppConfig.Server.IdleTimeout,
MaxHeaderBytes: models.AppConfig.Server.MaxHeaderBytes,
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
go func() {
log.Printf("Starting code-bench Portal Server on %s ...\n", port)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Server failed to start: %v", err)
}
}()
<-ctx.Done()
log.Println("Shutting down code-bench server ...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
log.Println("Server exited gracefully")
}