package ui import ( "bytes" "fmt" "html/template" "io" "net/http" "path/filepath" "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 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, Selected: id == clt.SelectedOption, }) } 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) { 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) } helpers.AddToContext(r, returncode, contentLength) }