You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

68 lines
1.5 KiB

  1. package controller
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/AFASystems/presence/internal/pkg/model"
  6. "github.com/gorilla/mux"
  7. "gorm.io/gorm"
  8. )
  9. func ZoneAddController(db *gorm.DB) http.HandlerFunc {
  10. return func(w http.ResponseWriter, r *http.Request) {
  11. var zone model.Zone
  12. if err := json.NewDecoder(r.Body).Decode(&zone); err != nil {
  13. http.Error(w, err.Error(), 400)
  14. return
  15. }
  16. db.Create(&zone)
  17. w.Write([]byte("ok"))
  18. }
  19. }
  20. func ZoneListController(db *gorm.DB) http.HandlerFunc {
  21. return func(w http.ResponseWriter, r *http.Request) {
  22. var zones []model.Zone
  23. db.Find(&zones)
  24. json.NewEncoder(w).Encode(zones) // Groups will appear as ["a", "b"] in JSON
  25. }
  26. }
  27. func ZoneUpdateController(db *gorm.DB) http.HandlerFunc {
  28. return func(w http.ResponseWriter, r *http.Request) {
  29. var zone model.Zone
  30. if err := json.NewDecoder(r.Body).Decode(&zone); err != nil {
  31. http.Error(w, err.Error(), 400)
  32. return
  33. }
  34. id := zone.ID
  35. if err := db.First(&model.Zone{}, "id = ?", id); err != nil {
  36. http.Error(w, "zone with this ID does not yet exist", 500)
  37. return
  38. }
  39. if err := db.Save(&zone).Error; err != nil {
  40. http.Error(w, err.Error(), 500)
  41. return
  42. }
  43. w.Write([]byte("ok"))
  44. }
  45. }
  46. func ZoneDeleteController(db *gorm.DB) http.HandlerFunc {
  47. return func(w http.ResponseWriter, r *http.Request) {
  48. id := mux.Vars(r)["id"]
  49. if res := db.Delete(&model.Zone{}, "id = ?", id); res.RowsAffected == 0 {
  50. http.Error(w, "no zone with such ID found", 400)
  51. return
  52. }
  53. w.Write([]byte("ok"))
  54. }
  55. }