WebUI/ui/ui.go
Theta-Dev 2e914a4095
All checks were successful
continuous-integration/drone/push Build is passing
fix spa pages not found
2022-02-07 01:26:02 +01:00

67 lines
1.2 KiB
Go

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)
}
}