package handler import ( "encoding/json" "fmt" "io" "net/http" "regexp" "strings" models "vctp/server/models" ) // VmModify receives the CloudEvent for a VM modification or move func (h *Handler) VmModify(w http.ResponseWriter, r *http.Request) { reqBody, err := io.ReadAll(r.Body) if err != nil { h.Logger.Error("Invalid data received", "error", err) fmt.Fprintf(w, "Invalid data received") w.WriteHeader(http.StatusInternalServerError) return } else { h.Logger.Debug("received input data", "length", len(reqBody)) } // Decode the JSON body into CloudEventReceived struct var event models.CloudEventReceived if err := json.Unmarshal(reqBody, &event); err != nil { h.Logger.Error("unable to decode json", "error", err) http.Error(w, "Invalid JSON body", http.StatusBadRequest) return } else { h.Logger.Debug("successfully decoded JSON") prettyPrint(event) } if event.CloudEvent.Data.ConfigChanges == nil { h.Logger.Debug("Received event contains no config change") } else { h.Logger.Debug("Received event contains config change info") config := h.processConfigChanges(event.CloudEvent.Data.ConfigChanges.Modified) prettyPrint(config) } /* // Map to hold the JSON data var config map[string]interface{} // Unmarshal the JSON into the map if len(*event.CloudEvent.Data.ConfigSpec) > 0 { err := json.Unmarshal([]byte(*event.CloudEvent.Data.ConfigSpec), &config) if err != nil { h.Logger.Error("unable to decode json", "error", err) http.Error(w, "Invalid JSON body", http.StatusBadRequest) return } } */ h.Logger.Debug("received update request", "body", string(reqBody)) w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "Update Request (%d): %v\n", len(reqBody), string(reqBody)) } func (h *Handler) processConfigChanges(configChanges string) []map[string]string { // Split the string on one or more consecutive newline characters changes := regexp.MustCompile(`\n+`).Split(configChanges, -1) // Regular expression to match config type and the new value after '->' or '<-' re := regexp.MustCompile(`(?P[^\s]+): \d+ -[><] (?P\w+);`) // Result will hold a list of changes with type and new value var result []map[string]string for _, change := range changes { // Trim any extra spaces and skip empty lines change = strings.TrimSpace(change) h.Logger.Debug("Processing config change element", "substring", change) if change == "" { continue } // Find the matches using the regex match := re.FindStringSubmatch(change) if len(match) > 0 { // Create a map with 'type' and 'newValue' changeMap := map[string]string{ "type": match[1], // config type "newValue": match[2], // new value after -> or <- } h.Logger.Debug("Adding new entry to output", "map", changeMap) result = append(result, changeMap) } else { h.Logger.Warn("No regex matches for string", "input", change) } } return result }