wolbodge/routes/index.go
2025-03-22 13:19:55 +01:00

72 lines
1.6 KiB
Go

package routes
import (
"html/template"
"net/http"
"strings"
"time"
"git.1e99.eu/1e99/wolbodge/devices"
"git.1e99.eu/1e99/wolbodge/sessions"
)
func GetIndex(device devices.Device, storage sessions.Storage, tmpl *template.Template) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
status, err := device.Status()
if err != nil {
return
}
sessions, err := storage.GetSessions()
if err != nil {
return
}
tmpl.Execute(res, map[string]any{
"DeviceStatus": status,
"Sessions": sessions,
})
}
}
func StartSession(storage sessions.Storage) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
err := req.ParseMultipartForm(10 * 1024)
if err != nil {
http.Error(res, "", http.StatusBadRequest)
return
}
description := req.FormValue("description")
if strings.TrimSpace(description) == "" {
description = "unknown"
}
_, err = storage.StartSession(description, time.Now())
if err != nil {
http.Error(res, "", http.StatusInternalServerError)
return
}
http.Redirect(res, req, "/", http.StatusFound)
}
}
func EndSession(storage sessions.Storage) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
err := req.ParseMultipartForm(10 * 1024)
if err != nil {
http.Error(res, "", http.StatusBadRequest)
return
}
sessionId := req.FormValue("session_id")
err = storage.EndSession(sessionId)
if err != nil {
http.Error(res, "", http.StatusInternalServerError)
return
}
http.Redirect(res, req, "/", http.StatusFound)
}
}