package routes import ( "basic-sensor-receiver/app" "log" "net/http" "github.com/gin-gonic/gin" ) type postOrPutSensorsBody struct { Name string `json:"name" binding:"required"` } func GetSensors(s *app.Server) gin.HandlerFunc { return func(c *gin.Context) { sensors, err := s.Services.Sensors.GetList() if err != nil { log.Println(err) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, sensors) } } func PostSensors(s *app.Server) gin.HandlerFunc { return func(c *gin.Context) { body := postOrPutSensorsBody{} if err := bindJSONBodyOrAbort(c, &body); err != nil { return } sensor, err := s.Services.Sensors.Create(body.Name) if err != nil { c.AbortWithError(http.StatusInternalServerError, err) return } c.JSON(http.StatusOK, sensor) } } func PutSensor(s *app.Server) gin.HandlerFunc { return func(c *gin.Context) { sensorId, err := getIntParamOrAbort(c, "sensor") if err != nil { return } body := postOrPutSensorsBody{} if err := bindJSONBodyOrAbort(c, &body); err != nil { return } sensor, err := s.Services.Sensors.Update(sensorId, body.Name) if err != nil { c.AbortWithError(http.StatusInternalServerError, err) return } c.JSON(http.StatusOK, sensor) } } func GetSensor(s *app.Server) gin.HandlerFunc { return func(c *gin.Context) { sensorId, err := getIntParamOrAbort(c, "sensor") if err != nil { return } body := postOrPutSensorsBody{} if err := bindJSONBodyOrAbort(c, &body); err != nil { return } sensor, err := s.Services.Sensors.GetById(sensorId) if err != nil { c.AbortWithError(http.StatusInternalServerError, err) return } c.JSON(http.StatusOK, sensor) } } func DeleteSensor(s *app.Server) gin.HandlerFunc { return func(c *gin.Context) { sensorId, err := getIntParamOrAbort(c, "sensor") if err != nil { return } err = s.Services.Sensors.DeleteById(sensorId) if err != nil { c.AbortWithError(http.StatusInternalServerError, err) return } c.Status(http.StatusOK) } }