blasphem/pkg/frontend/frontend.go
2022-12-20 19:05:45 -05:00

71 lines
1.2 KiB
Go

package frontend
import (
"embed"
"io"
"io/fs"
"net/http"
"sync"
"dynatron.me/x/blasphem/pkg/blas"
"dynatron.me/x/blasphem/pkg/blas/core"
"dynatron.me/x/blasphem/pkg/components"
"github.com/labstack/echo/v4"
)
const FrontendKey = "frontend"
//go:embed frontend/hass_frontend
var root embed.FS
type Frontend struct {
fsHandler echo.HandlerFunc
rootFS fs.FS
routeInstall sync.Once
}
func (fe *Frontend) InstallRoutes(e *echo.Echo) {
fe.routeInstall.Do(func() {
e.GET("/*", fe.fsHandler)
e.GET("/auth/authorize", fe.AliasHandler("authorize.html"))
})
}
func (fe *Frontend) AliasHandler(toFile string) echo.HandlerFunc {
return func(c echo.Context) error {
file, err := fe.rootFS.Open(toFile)
if err != nil {
return err
}
defer file.Close()
b, err := io.ReadAll(file)
if err != nil {
return err
}
return c.HTML(http.StatusOK, string(b))
}
}
func (*Frontend) Shutdown() {}
func Setup(_ core.Blas) (components.Component, error) {
fe := &Frontend{}
var err error
fe.rootFS, err = fs.Sub(root, "frontend/hass_frontend")
if err != nil {
return nil, err
}
fe.fsHandler = echo.StaticDirectoryHandler(fe.rootFS, false)
return fe, nil
}
func init() {
blas.Register(FrontendKey, Setup)
}