package main import ( "encoding/json" "fmt" "net/http" "github.com/gorilla/mux" ) // getBoxesHandler handles the GET /boxes endpoint. func GetBoxesHandler(w http.ResponseWriter, r *http.Request) { log := GetLogger() log.Info("Received %s request to %s", r.Method, r.URL) var boxes []Box db.Find(&boxes) json.NewEncoder(w).Encode(boxes) } func GetBoxHandler(w http.ResponseWriter, r *http.Request) { log := GetLogger() vars := mux.Vars(r) id := vars["id"] var box Box if err := db.First(&box, id).Error; err != nil { log.Warn("Box not found with ID: %s", id) http.Error(w, "Box not found", http.StatusNotFound) return } json.NewEncoder(w).Encode(box) } // createBoxHandler handles the POST /boxes endpoint. func CreateBoxHandler(w http.ResponseWriter, r *http.Request) { log := GetLogger() var box Box err := json.NewDecoder(r.Body).Decode(&box) if err != nil { log.Error("Failed to decode box creation request: %v", err) http.Error(w, "Invalid request body", http.StatusBadRequest) return } db.Create(&box) // Create a response struct to include the ID type createBoxResponse struct { ID uint `json:"id"` Name string `json:"name"` } response := createBoxResponse{ ID: box.ID, Name: box.Name, } log.DatabaseAction("create", fmt.Sprintf("Created box with ID %d", box.ID)) json.NewEncoder(w).Encode(response) } // deleteBoxHandler handles the DELETE /boxes/{id} endpoint. func DeleteBoxHandler(w http.ResponseWriter, r *http.Request) { log := GetLogger() vars := mux.Vars(r) id := vars["id"] // Retrieve the box from the database var box Box if err := db.First(&box, id).Error; err != nil { log.Warn("Attempt to delete non-existent box with ID: %s", id) http.Error(w, "Box not found", http.StatusNotFound) return } // Delete the box db.Delete(&box) log.DatabaseAction("delete", fmt.Sprintf("Deleted box with ID %d", box.ID)) w.WriteHeader(http.StatusNoContent) // 204 No Content }