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
+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)
})
}