Files
glchat/internal/server/static.go
T

86 lines
2.4 KiB
Go
Raw Normal View History

package server
import (
"errors"
"io/fs"
"mime"
"net/http"
"os"
"path"
"path/filepath"
"strings"
)
// staticHandler serves the built web client with SPA fallback: unknown paths
// return index.html so client-side routes survive a page reload.
type staticHandler struct {
root string
}
func newStaticHandler(root string) *staticHandler {
return &staticHandler{root: root}
}
func (h *staticHandler) serve(w http.ResponseWriter, r *http.Request) {
cleaned := path.Clean("/" + r.URL.Path)
rel := strings.TrimPrefix(cleaned, "/")
if rel == "" {
h.serveIndex(w, r)
return
}
info, err := fs.Stat(os.DirFS(h.root), rel)
if err != nil || info.IsDir() {
if err != nil && !errors.Is(err, fs.ErrNotExist) {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
h.serveIndex(w, r)
return
}
// Часть расширений (манифест PWA) известна не всем системам: тип задаём
// явно, иначе браузер получает text/plain и отказывается ставить приложение.
if contentType := staticContentType(rel); contentType != "" {
w.Header().Set("Content-Type", contentType)
}
if strings.HasPrefix(rel, "assets/") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
} else {
w.Header().Set("Cache-Control", "no-cache")
}
http.ServeFile(w, r, filepath.Join(h.root, filepath.FromSlash(rel)))
}
// staticContentType определяет тип файла: сначала явные правила, потом mime.
func staticContentType(rel string) string {
switch filepath.Ext(rel) {
case ".webmanifest":
return "application/manifest+json"
case ".js":
return "text/javascript; charset=utf-8"
case ".css":
return "text/css; charset=utf-8"
case ".svg":
return "image/svg+xml"
}
return mime.TypeByExtension(filepath.Ext(rel))
}
func (h *staticHandler) serveIndex(w http.ResponseWriter, r *http.Request) {
index := filepath.Join(h.root, "index.html")
if _, err := os.Stat(index); err != nil {
writeClientNotBuilt(w)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
http.ServeFile(w, r, index)
}
func writeClientNotBuilt(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte("glchat: web client bundle is not present in this image\n"))
}