diff --git a/backend/handlers.go b/backend/handlers.go index 1a0c579..1f44cb0 100644 --- a/backend/handlers.go +++ b/backend/handlers.go @@ -1,16 +1,15 @@ package backend import ( - "bytes" "context" "encoding/json" - "fmt" - "github.com/honeynet/ochi/backend/entities" - "github.com/julienschmidt/httprouter" - "google.golang.org/api/idtoken" "io" "net/http" "os" + + "github.com/honeynet/ochi/backend/entities" + "github.com/julienschmidt/httprouter" + "google.golang.org/api/idtoken" ) func (cs *server) indexHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { @@ -38,54 +37,36 @@ func (cs *server) cssHandler(w http.ResponseWriter, r *http.Request, _ httproute } } -// Helper function which splits into two parts the sensorID by the hyphen -func extractFirst8CharactersOfSensorId(sensorID string) (string, error) { - if len(sensorID) < 8 { - return "", fmt.Errorf("Sensor ID must have at least 8 characters") - } - return sensorID[:8], nil -} - // publishHandler reads the request body with a limit of 8192 bytes and then publishes // the received message. func (cs *server) publishHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { body := http.MaxBytesReader(w, r.Body, 8192) - msg, err := io.ReadAll(body) - if err != nil { - http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge) - return - } - defer body.Close() + // Unmarshal the JSON message into a map - decoder := json.NewDecoder(bytes.NewReader(msg)) + decoder := json.NewDecoder(body) + // Create a new map to store the sensorDataMap - var sensorIDMap map[string]interface{} + var sensorIDMap map[string]string // Decode into the sensorDataMap if err := decoder.Decode(&sensorIDMap); err != nil { - http.Error(w, "Invalid JSON payload", http.StatusBadRequest) - return - } - if sensorIDMap == nil { - // Handle the case where sensorMap is nil - http.Error(w, "Invalid JSON payload", http.StatusBadRequest) + http.Error(w, "JSON decoding error: "+err.Error(), http.StatusBadRequest) return } + // Get the sensorID from the map sensorID, exists := sensorIDMap["sensorID"] if !exists { http.Error(w, "Sensor Id does not exists.", http.StatusBadRequest) return } - sensorIDStr, ok := sensorID.(string) - if !ok { - http.Error(w, "Sensor ID is not a string.", http.StatusBadRequest) - return - } - sensorID, err = extractFirst8CharactersOfSensorId(sensorIDStr) - if err != nil { - http.Error(w, "Sensor ID is less than 8 characters.", http.StatusBadRequest) + + if len(sensorID) < 8 { + http.Error(w, "Sensor ID must have at least 8 characters.", http.StatusBadRequest) return } + + sensorID = sensorID[:8] + sensorIDMap["sensorID"] = sensorID // Convert the sensorID back to a JSON message alteredMsg, err := json.Marshal(sensorIDMap)