package client import ( "encoding/json" "fmt" "io" "net" "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 EnrollController struct { clientService *services.ClientHandlerService l *logrus.Logger } func NewEnrollController(l *logrus.Logger) *EnrollController { return &EnrollController{ clientService: services.NewClientHandlerService(), l: l, } } func (ec *EnrollController) enrollMachine(w http.ResponseWriter, r *http.Request) (int, error) { if r.Method != http.MethodPost { return http.StatusMethodNotAllowed, nil } clientIP, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return http.StatusInternalServerError, fmt.Errorf("failed to read remote IP: %w", err) } dat, err := io.ReadAll(r.Body) if err != nil { return http.StatusInternalServerError, fmt.Errorf("failed to read body: %w", err) } var client bootoption.Client if err := json.Unmarshal(dat, &client); err != nil { return http.StatusInternalServerError, fmt.Errorf("failed to parse body: %w", err) } client.IP = clientIP ec.clientService.AddClient(&client) ec.l.Infof("Added client %s", clientIP) return http.StatusAccepted, nil } func (ec *EnrollController) ServeHTTP(w http.ResponseWriter, r *http.Request) { returncode, err := ec.enrollMachine(w, r) if err != nil { ec.l.Errorf("Error handling client enrollement: %s", err.Error()) } helpers.HandleResponse(w, r, returncode, nil, ec.l) }