Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

83 righe
2.3 KiB

  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "github.com/AFASystems/presence/internal/pkg/api/response"
  7. "github.com/AFASystems/presence/internal/pkg/model"
  8. "github.com/gorilla/mux"
  9. "gorm.io/gorm"
  10. )
  11. func GatewayAddController(db *gorm.DB, context context.Context) http.HandlerFunc {
  12. return func(w http.ResponseWriter, r *http.Request) {
  13. var gateway model.Gateway
  14. if err := json.NewDecoder(r.Body).Decode(&gateway); err != nil {
  15. response.BadRequest(w, "invalid request body")
  16. return
  17. }
  18. if err := db.WithContext(context).Create(&gateway).Error; err != nil {
  19. response.InternalError(w, "failed to create gateway", err)
  20. return
  21. }
  22. response.JSON(w, http.StatusCreated, map[string]string{"status": "created"})
  23. }
  24. }
  25. func GatewayListController(db *gorm.DB, context context.Context) http.HandlerFunc {
  26. return func(w http.ResponseWriter, r *http.Request) {
  27. var gateways []model.Gateway
  28. if err := db.WithContext(context).Find(&gateways).Error; err != nil {
  29. response.InternalError(w, "failed to list gateways", err)
  30. return
  31. }
  32. response.JSON(w, http.StatusOK, gateways)
  33. }
  34. }
  35. func GatewayDeleteController(db *gorm.DB, context context.Context) http.HandlerFunc {
  36. return func(w http.ResponseWriter, r *http.Request) {
  37. id := mux.Vars(r)["id"]
  38. res := db.WithContext(context).Delete(&model.Gateway{}, "id = ?", id)
  39. if res.RowsAffected == 0 {
  40. response.NotFound(w, "gateway not found")
  41. return
  42. }
  43. if res.Error != nil {
  44. response.InternalError(w, "failed to delete gateway", res.Error)
  45. return
  46. }
  47. response.JSON(w, http.StatusOK, map[string]string{"status": "deleted"})
  48. }
  49. }
  50. func GatewayUpdateController(db *gorm.DB, context context.Context) http.HandlerFunc {
  51. return func(w http.ResponseWriter, r *http.Request) {
  52. id := mux.Vars(r)["id"]
  53. if err := db.WithContext(context).First(&model.Gateway{}, "id = ?", id).Error; err != nil {
  54. response.NotFound(w, "gateway not found")
  55. return
  56. }
  57. var gateway model.Gateway
  58. if err := json.NewDecoder(r.Body).Decode(&gateway); err != nil {
  59. response.BadRequest(w, "invalid request body")
  60. return
  61. }
  62. if err := db.WithContext(context).Save(&gateway).Error; err != nil {
  63. response.InternalError(w, "failed to update gateway", err)
  64. return
  65. }
  66. response.JSON(w, http.StatusOK, map[string]string{"status": "updated"})
  67. }
  68. }