Fix embedded frontend serving: use fs.ReadFile instead of Gin FileFromFS

- FileFromFS with http.FS(embedFS) returned 301 redirects due to
  Gin setting c.Request.URL.Path to a relative path for http.FileServer
- Replace with direct fs.ReadFile + Gin c.Data, determining content
  type via mime.TypeByExtension
- Supports all asset types (JS, CSS, SVG, HTML) and SPA fallback
This commit is contained in:
MrFastwind
2026-07-09 15:34:50 +02:00
parent bc0a252d7d
commit 9aa6fca50e

View File

@@ -4,10 +4,12 @@ import (
"context"
"io/fs"
"log"
"mime"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
@@ -59,10 +61,22 @@ func main() {
subFS, subErr := fs.Sub(embed.Frontend, "dist")
if subErr == nil {
if _, err := subFS.Open("index.html"); err == nil {
r.StaticFS("/assets", http.FS(subFS))
r.StaticFileFS("/favicon.ico", "favicon.ico", http.FS(subFS))
r.NoRoute(func(c *gin.Context) {
c.FileFromFS("index.html", http.FS(subFS))
path := strings.TrimPrefix(c.Request.URL.Path, "/")
if path == "" {
path = "index.html"
}
data, err := fs.ReadFile(subFS, path)
if err == nil {
ct := mime.TypeByExtension(filepath.Ext(path))
if ct == "" {
ct = "text/html; charset=utf-8"
}
c.Data(http.StatusOK, ct, data)
return
}
data, _ = fs.ReadFile(subFS, "index.html")
c.Data(http.StatusOK, "text/html; charset=utf-8", data)
})
log.Print("serving embedded frontend")
}