You've already forked agentic-coding-workflow
35 lines
960 B
Go
35 lines
960 B
Go
// 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)
|
|
})
|
|
}
|