25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

74 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 GatewayAddController(db *gorm.DB) http.HandlerFunc {
  10. return func(w http.ResponseWriter, r *http.Request) {
  11. decoder := json.NewDecoder(r.Body)
  12. var gateway model.Gateway
  13. if err := decoder.Decode(&gateway); err != nil {
  14. http.Error(w, err.Error(), 400)
  15. return
  16. }
  17. db.Create(&gateway)
  18. w.Write([]byte("ok"))
  19. }
  20. }
  21. func GatewayListController(db *gorm.DB) http.HandlerFunc {
  22. return func(w http.ResponseWriter, r *http.Request) {
  23. var gateways []model.Gateway
  24. db.Find(&gateways)
  25. res, err := json.Marshal(gateways)
  26. if err != nil {
  27. http.Error(w, err.Error(), 400)
  28. return
  29. }
  30. w.Write(res)
  31. }
  32. }
  33. func GatewayDeleteController(db *gorm.DB) http.HandlerFunc {
  34. return func(w http.ResponseWriter, r *http.Request) {
  35. id := mux.Vars(r)["id"]
  36. if res := db.Delete(&model.Gateway{}, "id = ?", id); res.RowsAffected == 0 {
  37. http.Error(w, "no gateway with such ID found", 400)
  38. return
  39. }
  40. w.Write([]byte("ok"))
  41. }
  42. }
  43. func GatewayUpdateController(db *gorm.DB) http.HandlerFunc {
  44. return func(w http.ResponseWriter, r *http.Request) {
  45. id := mux.Vars(r)["id"]
  46. if err := db.First(&model.Gateway{}, "id = ?", id).Error; err != nil {
  47. http.Error(w, err.Error(), 400)
  48. return
  49. }
  50. decoder := json.NewDecoder(r.Body)
  51. var gateway model.Gateway
  52. if err := decoder.Decode(&gateway); err != nil {
  53. http.Error(w, err.Error(), 400)
  54. return
  55. }
  56. db.Save(&gateway)
  57. w.Write([]byte("ok"))
  58. }
  59. }