36 lines
728 B
Go
36 lines
728 B
Go
package httpapi
|
|
|
|
import (
|
|
"embed"
|
|
"io/fs"
|
|
"net/http"
|
|
)
|
|
|
|
//go:embed all:webdist
|
|
var webDist embed.FS
|
|
|
|
func (s *Server) staticHandler() http.Handler {
|
|
sub, err := fs.Sub(webDist, "webdist")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
fileServer := http.FileServer(http.FS(sub))
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// SPA fallback: если файла нет — отдать index.html
|
|
if _, err := fs.Stat(sub, trimLead(r.URL.Path)); err != nil && r.URL.Path != "/" {
|
|
r2 := r.Clone(r.Context())
|
|
r2.URL.Path = "/"
|
|
fileServer.ServeHTTP(w, r2)
|
|
return
|
|
}
|
|
fileServer.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func trimLead(p string) string {
|
|
if len(p) > 0 && p[0] == '/' {
|
|
return p[1:]
|
|
}
|
|
return p
|
|
}
|