|
- package controller
-
- import (
- "encoding/json"
- "net/http"
-
- "github.com/AFASystems/presence/internal/pkg/model"
- "github.com/gorilla/mux"
- "gorm.io/gorm"
- )
-
- func GatewayAddController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- decoder := json.NewDecoder(r.Body)
- var gateway model.Gateway
-
- if err := decoder.Decode(&gateway); err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- db.Create(&gateway)
- w.Write([]byte("ok"))
- }
- }
-
- func GatewayListController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- var gateways []model.Gateway
- db.Find(&gateways)
- res, err := json.Marshal(gateways)
- if err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- w.Write(res)
- }
- }
-
- func GatewayDeleteController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
- if res := db.Delete(&model.Gateway{}, "id = ?", id); res.RowsAffected == 0 {
- http.Error(w, "no gateway with such ID found", 400)
- return
- }
-
- w.Write([]byte("ok"))
- }
- }
-
- func GatewayUpdateController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
-
- if err := db.First(&model.Gateway{}, "id = ?", id).Error; err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- decoder := json.NewDecoder(r.Body)
- var gateway model.Gateway
-
- if err := decoder.Decode(&gateway); err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- db.Save(&gateway)
- w.Write([]byte("ok"))
- }
- }
|