http-boot-server/bootserver/controllers/client/enroll.go
Melora Hugues 5ad1f6ae43
Some checks failed
continuous-integration/drone/push Build is failing
tmp to fixup for main
2023-09-01 18:42:37 +02:00

76 lines
2.2 KiB
Go

package client
import (
"encoding/json"
"fmt"
"io"
"net/http"
"git.faercol.me/faercol/http-boot-server/bootserver/bootoption"
"git.faercol.me/faercol/http-boot-server/bootserver/helpers"
"git.faercol.me/faercol/http-boot-server/bootserver/services"
"github.com/sirupsen/logrus"
)
const EnrollRoute = "/enroll"
type newClientPayload struct {
ID string `json:"ID"`
MulticastGroup string `json:"multicast_group"`
MulticastPort int `json:"multicast_port"`
}
type EnrollController struct {
clientService *services.ClientHandlerService
l *logrus.Logger
multicastPort int
multicastGroup string
}
func NewEnrollController(l *logrus.Logger, service *services.ClientHandlerService, mcastPort int, mcastGroup string) *EnrollController {
return &EnrollController{
clientService: service,
l: l,
multicastPort: mcastPort,
multicastGroup: mcastGroup,
}
}
func (ec *EnrollController) enrollMachine(w http.ResponseWriter, r *http.Request) (int, []byte, error) {
if r.Method != http.MethodPost {
return http.StatusMethodNotAllowed, nil, nil
}
dat, err := io.ReadAll(r.Body)
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to read body: %w", err)
}
var client bootoption.Client
if err := json.Unmarshal(dat, &client); err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to parse body: %w", err)
}
cltID, err := ec.clientService.AddClient(&client)
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to create client %w", err)
}
payload, err := json.Marshal(newClientPayload{ID: cltID.String(), MulticastGroup: ec.multicastGroup, MulticastPort: ec.multicastPort})
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to serialize payload: %w", err)
}
ec.l.Infof("Added client")
w.Header().Add("Content-Type", "application/json")
return http.StatusOK, payload, nil
}
func (ec *EnrollController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
returncode, content, err := ec.enrollMachine(w, r)
if err != nil {
ec.l.Errorf("Error handling client enrollement: %s", err.Error())
}
helpers.HandleResponse(w, r, returncode, content, ec.l)
}