Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

69 řádky
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. // controller/tracker_controller.go
  10. func TrackerAddController(db *gorm.DB) http.HandlerFunc {
  11. return func(w http.ResponseWriter, r *http.Request) {
  12. var tz model.TrackerZones
  13. if err := json.NewDecoder(r.Body).Decode(&tz); err != nil {
  14. http.Error(w, err.Error(), 400)
  15. return
  16. }
  17. db.Create(&tz)
  18. w.Write([]byte("ok"))
  19. }
  20. }
  21. func TrackerListController(db *gorm.DB) http.HandlerFunc {
  22. return func(w http.ResponseWriter, r *http.Request) {
  23. var list []model.TrackerZones
  24. db.Find(&list)
  25. json.NewEncoder(w).Encode(list)
  26. }
  27. }
  28. func TrackerUpdateController(db *gorm.DB) http.HandlerFunc {
  29. return func(w http.ResponseWriter, r *http.Request) {
  30. var tz model.TrackerZones
  31. if err := json.NewDecoder(r.Body).Decode(&tz); err != nil {
  32. http.Error(w, "Invalid JSON", 400)
  33. return
  34. }
  35. id := tz.ID
  36. if err := db.First(&model.TrackerZones{}, "id = ?", id).Error; err != nil {
  37. http.Error(w, err.Error(), 400)
  38. return
  39. }
  40. if err := db.Save(&tz).Error; err != nil {
  41. http.Error(w, err.Error(), 500)
  42. return
  43. }
  44. w.Write([]byte("ok"))
  45. }
  46. }
  47. func TrackerDeleteController(db *gorm.DB) http.HandlerFunc {
  48. return func(w http.ResponseWriter, r *http.Request) {
  49. id := mux.Vars(r)["id"]
  50. if res := db.Delete(&model.TrackerZones{}, "id = ?", id); res.RowsAffected == 0 {
  51. http.Error(w, "no tracker zone with such ID found", 400)
  52. return
  53. }
  54. w.Write([]byte("ok"))
  55. }
  56. }