miniwol/web/web.go

79 lines
1.6 KiB
Go
Raw Permalink Normal View History

2022-02-17 12:31:01 +00:00
package web
import (
2022-02-18 13:35:03 +00:00
"bytes"
2022-02-17 12:31:01 +00:00
"embed"
"html/template"
2022-02-18 13:35:03 +00:00
2022-02-18 14:34:33 +00:00
"git.ulra.eu/adro/miniwol/config"
2022-02-18 13:35:03 +00:00
"github.com/labstack/echo/v4"
2022-02-17 12:31:01 +00:00
)
//go:embed template/*
var templateFS embed.FS
2022-02-18 13:35:03 +00:00
var templates *template.Template
2022-02-17 12:31:01 +00:00
func init() {
var err error
templates, err = template.ParseFS(templateFS, "template/*.html")
2022-02-17 12:31:01 +00:00
if err != nil {
panic(err)
}
2022-02-18 13:35:03 +00:00
}
func Run() error {
e := echo.New()
e.GET("/", index)
e.GET("/style.css", style)
2022-02-18 13:35:03 +00:00
e.POST("/auth", auth)
e.POST("/deauth", withAuth(deauth))
e.POST("/add", withAuth(add))
2022-02-18 13:35:03 +00:00
e.POST("/wake", withAuth(wake))
e.POST("/remove", withAuth(remove))
2022-02-18 13:35:03 +00:00
return e.Start(config.Config.Server)
}
func Page(c echo.Context, code int, title string, page string, auth bool, data interface{}) error {
2022-02-18 13:35:03 +00:00
var contentBuffer bytes.Buffer
err := templates.ExecuteTemplate(&contentBuffer, page, data)
2022-02-17 12:31:01 +00:00
if err != nil {
2022-02-18 13:35:03 +00:00
return err
2022-02-17 12:31:01 +00:00
}
2022-02-18 13:35:03 +00:00
var pageBuffer bytes.Buffer
err = templates.ExecuteTemplate(&pageBuffer, "page.html", struct {
2022-02-18 13:35:03 +00:00
Title string
Content template.HTML
Auth bool
2022-02-18 13:35:03 +00:00
}{
Title: title,
Content: template.HTML(contentBuffer.String()),
Auth: auth,
2022-02-18 13:35:03 +00:00
})
2022-02-17 12:31:01 +00:00
if err != nil {
2022-02-18 13:35:03 +00:00
return err
2022-02-17 12:31:01 +00:00
}
2022-02-18 13:35:03 +00:00
return c.HTML(code, pageBuffer.String())
}
2022-02-17 12:31:01 +00:00
2022-02-18 13:35:03 +00:00
// 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)
2022-02-18 13:35:03 +00:00
} else {
return Page(c, 200, "Devices", "device.html", true, config.Config)
2022-02-17 12:31:01 +00:00
}
}
func style(c echo.Context) error {
styleData, err := templateFS.ReadFile("template/style.css")
if err != nil {
return err
2022-02-18 13:35:03 +00:00
}
return c.Blob(200, "text/css", styleData)
2022-02-17 12:31:01 +00:00
}