63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"io"
|
|
"io/fs"
|
|
"net/http"
|
|
"path"
|
|
"strings"
|
|
|
|
"git.asio.asia/TapRemly/server/internal/webui"
|
|
)
|
|
|
|
func (h *Handler) spa() http.Handler {
|
|
sub, err := fs.Sub(webui.Dist, "dist")
|
|
if err != nil {
|
|
return http.NotFoundHandler()
|
|
}
|
|
if _, err := fs.Stat(sub, "index.html"); err != nil {
|
|
return http.NotFoundHandler()
|
|
}
|
|
files := http.FileServer(http.FS(sub))
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
rel := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
|
|
if rel == "" || rel == "." {
|
|
serveIndex(w, r, sub)
|
|
return
|
|
}
|
|
info, err := fs.Stat(sub, rel)
|
|
if err == nil && !info.IsDir() {
|
|
if strings.HasPrefix(rel, "assets/") {
|
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
|
}
|
|
files.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
if path.Ext(rel) != "" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
serveIndex(w, r, sub)
|
|
})
|
|
}
|
|
|
|
func serveIndex(w http.ResponseWriter, r *http.Request, fsys fs.FS) {
|
|
f, err := fsys.Open("index.html")
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
defer f.Close()
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
w.WriteHeader(http.StatusOK)
|
|
if r.Method == http.MethodHead {
|
|
return
|
|
}
|
|
_, _ = io.Copy(w, f)
|
|
}
|