wolbodge/routes/index.go
2025-03-22 15:42:01 +01:00

79 lines
1.9 KiB
Go

package routes
import (
"html/template"
"log"
"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(logger *log.Logger, 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"
}
session, err := storage.StartSession(description, time.Now())
if err != nil {
http.Error(res, "", http.StatusInternalServerError)
return
}
http.Redirect(res, req, "/", http.StatusFound)
logger.Printf("Started new session for %s via webpanel (id = %s, description = \"%s\")", req.RemoteAddr, session.Id, session.Description)
}
}
func EndSession(logger *log.Logger, 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)
switch {
case err == sessions.ErrUnknownSession:
http.Error(res, "", http.StatusNotFound)
return
case err != nil:
http.Error(res, "", http.StatusInternalServerError)
return
}
http.Redirect(res, req, "/", http.StatusFound)
logger.Printf("Ended session for %s via webpanel (id = %s)", req.RemoteAddr, sessionId)
}
}