feat(server): embed SPA dist with fallback handler; single-binary deploy

This commit is contained in:
2026-04-29 10:43:42 +08:00
parent 04a19dbcef
commit 78989a42ac
8 changed files with 70 additions and 2 deletions
+12 -1
View File
@@ -18,8 +18,10 @@ package app
import (
"context"
"embed"
"errors"
"fmt"
"io/fs"
"log/slog"
"net/http"
"time"
@@ -43,7 +45,9 @@ type App struct {
}
// New 把所有模块按启动顺序拼装好。任何阶段失败都会返回错误,不留半成品资源。
func New(ctx context.Context, cfg *config.Config) (*App, error) {
// dist 是 cmd/server 用 //go:embed 注入的前端构建产物,根目录为 web/dist;
// fs.Sub 之后交给 SPA handler 提供静态文件 + index.html 回退。
func New(ctx context.Context, cfg *config.Config, dist embed.FS) (*App, error) {
log := logger.FromEnv(cfg.Env, nil)
// 跑 migrations 必须在开池前;否则首次启动连不存在的表会让 ping 失败。
@@ -68,6 +72,12 @@ func New(ctx context.Context, cfg *config.Config) (*App, error) {
// 通过 App 字段透出去,目前保留局部变量以避免暴露未稳定 API。
_ = notifyDispatcher
spaSub, err := fs.Sub(dist, "web/dist")
if err != nil {
return nil, fmt.Errorf("sub fs: %w", err)
}
spaHandler := httpx.NewSPAHandler(spaSub)
r := httpx.NewRouter(httpx.RouterDeps{
HealthCheck: func(req *http.Request) error {
return db.HealthCheck(req.Context(), pool)
@@ -75,6 +85,7 @@ func New(ctx context.Context, cfg *config.Config) (*App, error) {
ReadyCheck: func(req *http.Request) error {
return db.HealthCheck(req.Context(), pool)
},
SPAHandler: spaHandler,
})
// chi.Router 接口本身已经声明 Use,无需类型断言到 *chi.Mux。
+7
View File
@@ -17,6 +17,9 @@ type RouterDeps struct {
HealthCheck func(*http.Request) error
// ReadyCheck is invoked from GET /readyz with the same contract.
ReadyCheck func(*http.Request) error
// SPAHandler 为 nil 时禁用前端 fallback;非 nil 时挂到 chi NotFound,
// 把未匹配的请求交给 SPA handler 处理(静态文件 + index.html 回退)。
SPAHandler http.Handler
}
// NewRouter builds the application's chi.Router with the standard
@@ -46,5 +49,9 @@ func NewRouter(deps RouterDeps) chi.Router {
_, _ = w.Write([]byte("ok"))
})
if deps.SPAHandler != nil {
r.NotFound(deps.SPAHandler.ServeHTTP)
}
return r
}
+34
View File
@@ -0,0 +1,34 @@
// Package httpx 内的 spa.go 提供 SPA 静态资源 + 404 fallback。
// 命中文件直接 ServeFile;不存在但路径无后缀视为前端路由,回退 index.html;
// /api/ 前缀始终返回 404(避免把 API 拼写错误掩盖成 HTML)。
package httpx
import (
"errors"
"io/fs"
"net/http"
"strings"
)
// NewSPAHandler 把 distFS 暴露成 SPA handler。
func NewSPAHandler(distFS fs.FS) http.Handler {
fileServer := http.FileServer(http.FS(distFS))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
http.NotFound(w, r)
return
}
path := strings.TrimPrefix(r.URL.Path, "/")
if path == "" {
path = "index.html"
}
if _, err := fs.Stat(distFS, path); err != nil {
if errors.Is(err, fs.ErrNotExist) && !strings.Contains(path, ".") {
r.URL.Path = "/index.html"
fileServer.ServeHTTP(w, r)
return
}
}
fileServer.ServeHTTP(w, r)
})
}