feat: single Docker image with frontend served from backend
- Dockerfile: 3-stage build (frontend npm build → backend go build → alpine runtime) - Frontend dist files served from disk at /app/frontend/dist - server.go: catch-all GET handler serves static files with SPA fallback to index.html - config.go: new server.frontend_dir option (env: SUB_STORE_SERVER_FRONTEND_DIR) - API routes (/api/*), download routes, and /health take priority over static serving
This commit is contained in:
@@ -129,6 +129,14 @@ func startFiber(cfg *config.Config, db *sqlx.DB) error {
|
||||
return c.JSON(fiber.Map{"status": "ok"})
|
||||
})
|
||||
|
||||
// Serve frontend static files with SPA fallback.
|
||||
// Registered after API/download routes so those take priority.
|
||||
frontendDir := cfg.Server.FrontendDir
|
||||
if frontendDir == "" {
|
||||
frontendDir = "./frontend/dist"
|
||||
}
|
||||
registerStaticFrontend(app, frontendDir)
|
||||
|
||||
// Start server
|
||||
addr := fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port)
|
||||
logrus.Infof("Starting %s on %s", cfg.App.Name, addr)
|
||||
@@ -159,3 +167,33 @@ func startFiber(cfg *config.Config, db *sqlx.DB) error {
|
||||
logrus.Info("Server stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
// registerStaticFrontend serves static files from the given directory with
|
||||
// SPA fallback: any GET request that doesn't match a real file returns
|
||||
// index.html (so client-side routing works on fresh page loads).
|
||||
func registerStaticFrontend(app *fiber.App, dir string) {
|
||||
if _, err := os.Stat(dir); err != nil {
|
||||
logrus.WithError(err).Warn("frontend directory not found, static serving disabled")
|
||||
return
|
||||
}
|
||||
|
||||
indexFile := filepath.Join(dir, "index.html")
|
||||
|
||||
// Catch-all GET handler: try to serve the requested file from the dist
|
||||
// directory; if the file doesn't exist, fall back to index.html (SPA).
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
if c.Method() != "GET" {
|
||||
return c.Next()
|
||||
}
|
||||
path := c.Path()
|
||||
|
||||
// Try the exact file in the dist directory
|
||||
filePath := filepath.Join(dir, filepath.Clean(path))
|
||||
if info, err := os.Stat(filePath); err == nil && !info.IsDir() {
|
||||
return c.SendFile(filePath)
|
||||
}
|
||||
|
||||
// SPA fallback → index.html
|
||||
return c.SendFile(indexFile)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user