package ui import ( "bytes" "embed" "encoding/json" "io/fs" "net/http" "code.thetadev.de/TSGRain/WebUI/src/server/middleware" "code.thetadev.de/TSGRain/WebUI/src/util" "github.com/gin-gonic/gin" ) const distDir = "dist" //go:embed dist/** var assets embed.FS type uiConfig struct { Version string `json:"version"` NZones int32 `json:"n_zones"` } func subFS(fsys fs.FS, dir string) fs.FS { sub, err := fs.Sub(fsys, dir) if err != nil { panic(err) } return sub } func distFS() fs.FS { return subFS(assets, distDir) } func Register(r gin.IRouter, nZones int32) { indexHandler := getIndexHandler(nZones) uiAssets := r.Group("/assets", middleware.Cache) r.GET("/", indexHandler) r.GET("/:path", indexHandler) r.GET("/index.html", indexHandler) uiAssets.StaticFS("/", http.FS(subFS(distFS(), "assets"))) } func getIndexHandler(nZones int32) gin.HandlerFunc { content, err := fs.ReadFile(distFS(), "index.html") if err != nil { panic(err) } uiConfigBytes, err := json.Marshal(uiConfig{ Version: util.Version(), NZones: nZones, }) if err != nil { panic(err) } content = bytes.ReplaceAll(content, []byte("\"%CONFIG%\""), uiConfigBytes) return func(c *gin.Context) { c.Data(200, "text/html", content) } }