|
- package controller
-
- import (
- "encoding/json"
- "net/http"
-
- "github.com/AFASystems/presence/internal/pkg/model"
- "github.com/gorilla/mux"
- "gorm.io/gorm"
- )
-
- // controller/tracker_controller.go
- func TrackerAddController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- var tz model.TrackerZones
- if err := json.NewDecoder(r.Body).Decode(&tz); err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
- db.Create(&tz)
- w.Write([]byte("ok"))
- }
- }
-
- func TrackerListController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- var list []model.TrackerZones
- db.Find(&list)
- json.NewEncoder(w).Encode(list)
- }
- }
-
- func TrackerUpdateController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- var tz model.TrackerZones
-
- if err := json.NewDecoder(r.Body).Decode(&tz); err != nil {
- http.Error(w, "Invalid JSON", 400)
- return
- }
-
- id := tz.ID
-
- if err := db.First(&model.TrackerZones{}, "id = ?", id).Error; err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- if err := db.Save(&tz).Error; err != nil {
- http.Error(w, err.Error(), 500)
- return
- }
-
- w.Write([]byte("ok"))
- }
- }
-
- func TrackerDeleteController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
- if res := db.Delete(&model.TrackerZones{}, "id = ?", id); res.RowsAffected == 0 {
- http.Error(w, "no tracker zone with such ID found", 400)
- return
- }
-
- w.Write([]byte("ok"))
- }
- }
|