package controller import ( "encoding/json" "net/http" "github.com/AFASystems/presence/internal/pkg/model" "github.com/gorilla/mux" "gorm.io/gorm" ) func ZoneAddController(db *gorm.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var zone model.Zone if err := json.NewDecoder(r.Body).Decode(&zone); err != nil { http.Error(w, err.Error(), 400) return } db.Create(&zone) w.Write([]byte("ok")) } } func ZoneListController(db *gorm.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var zones []model.Zone db.Find(&zones) json.NewEncoder(w).Encode(zones) // Groups will appear as ["a", "b"] in JSON } } func ZoneUpdateController(db *gorm.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var zone model.Zone if err := json.NewDecoder(r.Body).Decode(&zone); err != nil { http.Error(w, err.Error(), 400) return } id := zone.ID if err := db.First(&model.Zone{}, "id = ?", id); err != nil { http.Error(w, "zone with this ID does not yet exist", 500) return } if err := db.Save(&zone).Error; err != nil { http.Error(w, err.Error(), 500) return } w.Write([]byte("ok")) } } func ZoneDeleteController(db *gorm.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] if res := db.Delete(&model.Zone{}, "id = ?", id); res.RowsAffected == 0 { http.Error(w, "no zone with such ID found", 400) return } w.Write([]byte("ok")) } }