You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

78 lines
1.6 KiB

  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "github.com/AFASystems/presence/internal/pkg/model"
  7. "github.com/gorilla/mux"
  8. "gorm.io/gorm"
  9. )
  10. func GatewayAddController(db *gorm.DB) http.HandlerFunc {
  11. return func(w http.ResponseWriter, r *http.Request) {
  12. decoder := json.NewDecoder(r.Body)
  13. var gateway model.Gateway
  14. if err := decoder.Decode(&gateway); err != nil {
  15. http.Error(w, err.Error(), 400)
  16. return
  17. }
  18. db.Create(&gateway)
  19. w.Write([]byte("ok"))
  20. }
  21. }
  22. func GatewayListController(db *gorm.DB) http.HandlerFunc {
  23. return func(w http.ResponseWriter, r *http.Request) {
  24. var gateways []model.Gateway
  25. db.Find(&gateways)
  26. fmt.Printf("gateways: %+v", gateways)
  27. res, err := json.Marshal(gateways)
  28. if err != nil {
  29. http.Error(w, err.Error(), 400)
  30. return
  31. }
  32. w.Write(res)
  33. }
  34. }
  35. func GatewayDeleteController(db *gorm.DB) http.HandlerFunc {
  36. return func(w http.ResponseWriter, r *http.Request) {
  37. vars := mux.Vars(r)
  38. id := vars["gateway_id"]
  39. if res := db.Delete(&model.Gateway{}, "id = ?", id); res.RowsAffected == 0 {
  40. http.Error(w, "no gateway with such ID found", 400)
  41. return
  42. }
  43. w.Write([]byte("ok"))
  44. }
  45. }
  46. func GatewayUpdateController(db *gorm.DB) http.HandlerFunc {
  47. return func(w http.ResponseWriter, r *http.Request) {
  48. vars := mux.Vars(r)
  49. id := vars["gateway_id"]
  50. if err := db.First(&model.Gateway{}, id).Error; err != nil {
  51. http.Error(w, err.Error(), 400)
  52. return
  53. }
  54. decoder := json.NewDecoder(r.Body)
  55. var gateway model.Gateway
  56. if err := decoder.Decode(&gateway); err != nil {
  57. http.Error(w, err.Error(), 400)
  58. return
  59. }
  60. db.Save(&gateway)
  61. w.Write([]byte("ok"))
  62. }
  63. }