miniwol/web/web.go
adro 2485c7ab7a Features, Polish, Improvements
- Added logout, add/remove devices
- Page structure w/ dark theme
- Template files now use target extension
- Accessibility improvements
- Semantic improvements
2022-02-21 15:16:06 +01:00

79 lines
1.6 KiB
Go

package web
import (
"bytes"
"embed"
"html/template"
"git.ulra.eu/adro/miniwol/config"
"github.com/labstack/echo/v4"
)
//go:embed template/*
var templateFS embed.FS
var templates *template.Template
func init() {
var err error
templates, err = template.ParseFS(templateFS, "template/*.html")
if err != nil {
panic(err)
}
}
func Run() error {
e := echo.New()
e.GET("/", index)
e.GET("/style.css", style)
e.POST("/auth", auth)
e.POST("/deauth", withAuth(deauth))
e.POST("/add", withAuth(add))
e.POST("/wake", withAuth(wake))
e.POST("/remove", withAuth(remove))
return e.Start(config.Config.Server)
}
func Page(c echo.Context, code int, title string, page string, auth bool, data interface{}) error {
var contentBuffer bytes.Buffer
err := templates.ExecuteTemplate(&contentBuffer, page, data)
if err != nil {
return err
}
var pageBuffer bytes.Buffer
err = templates.ExecuteTemplate(&pageBuffer, "page.html", struct {
Title string
Content template.HTML
Auth bool
}{
Title: title,
Content: template.HTML(contentBuffer.String()),
Auth: auth,
})
if err != nil {
return err
}
return c.HTML(code, pageBuffer.String())
}
// Handlers
func index(c echo.Context) error {
session, err := c.Cookie("session")
if err != nil || checkAuth(session.Value) != nil {
return Page(c, 200, "Login", "login.html", false, nil)
} else {
return Page(c, 200, "Devices", "device.html", true, config.Config)
}
}
func style(c echo.Context) error {
styleData, err := templateFS.ReadFile("template/style.css")
if err != nil {
return err
}
return c.Blob(200, "text/css", styleData)
}