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"` } type EnrollController struct { clientService *services.ClientHandlerService l *logrus.Logger } func NewEnrollController(l *logrus.Logger, service *services.ClientHandlerService) *EnrollController { return &EnrollController{ clientService: service, l: l, } } 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()}) if err != nil { return http.StatusInternalServerError, nil, fmt.Errorf("failed to serialize payload: %w", err) } ec.l.Infof("Added client") 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) }