http-boot-server/bootserver/controllers/ui/ui.go

109 lines
2.6 KiB
Go
Raw Normal View History

2023-08-16 21:33:26 +00:00
package ui
import (
"bytes"
"fmt"
"html/template"
"io"
"net/http"
"path/filepath"
"sort"
2023-08-16 21:33:26 +00:00
"git.faercol.me/faercol/http-boot-server/bootserver/helpers"
"git.faercol.me/faercol/http-boot-server/bootserver/services"
"github.com/sirupsen/logrus"
)
const UIRoute = "/"
type templateBootOption struct {
ID string
Name string
Path string
DiskID string
2023-08-16 21:33:26 +00:00
Selected bool
}
type templateClient struct {
ID string
Name string
BootOptions []templateBootOption
}
type templateData struct {
Clients []templateClient
}
type UIController struct {
clientService *services.ClientHandlerService
l *logrus.Logger
}
func NewUIController(l *logrus.Logger, service *services.ClientHandlerService) *UIController {
return &UIController{
clientService: service,
l: l,
}
}
func (uc *UIController) serveUI(w http.ResponseWriter, r *http.Request) (int, int, error) {
lp := filepath.Join("templates", "index.html")
tmpl, err := template.ParseFiles(lp)
if err != nil {
return http.StatusInternalServerError, -1, fmt.Errorf("failed to init template: %w", err)
}
buf := new(bytes.Buffer)
clients, err := uc.clientService.GetAllClientConfig()
if err != nil {
return http.StatusInternalServerError, -1, fmt.Errorf("failed to get list of clients: %w", err)
}
dat := templateData{Clients: []templateClient{}}
for _, clt := range clients {
tplBO := []templateBootOption{}
for id, bo := range clt.Options {
tplBO = append(tplBO, templateBootOption{
Name: bo.Name,
Path: bo.Path,
ID: id,
DiskID: bo.DiskID,
2023-08-16 21:33:26 +00:00
Selected: id == clt.SelectedOption,
})
sort.Slice(tplBO, func(i, j int) bool {
return tplBO[i].ID < tplBO[j].ID
})
2023-08-16 21:33:26 +00:00
}
dat.Clients = append(dat.Clients, templateClient{
ID: clt.ID.String(),
Name: clt.Name,
BootOptions: tplBO,
})
}
if err := tmpl.Execute(buf, dat); err != nil {
return http.StatusInternalServerError, -1, fmt.Errorf("failed to execute template: %w", err)
}
n, err := io.Copy(w, buf)
if err != nil {
return http.StatusInternalServerError, int(n), fmt.Errorf("failed to write response; %w", err)
}
return http.StatusOK, int(n), nil
}
func (uc *UIController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
uc.l.Errorf("Unhandled route %q", r.RequestURI)
helpers.HandleResponse(w, r, http.StatusNotFound, nil, uc.l)
return
}
2023-08-16 21:33:26 +00:00
returncode, contentLength, err := uc.serveUI(w, r)
if err != nil {
uc.l.Errorf("Error serving UI: %s", err.Error())
helpers.HandleResponse(w, r, returncode, nil, uc.l)
} else {
helpers.AddToContext(r, returncode, contentLength)
2023-08-16 21:33:26 +00:00
}
}