From fc3350efcc6b4d27088f8e62579cc4f381f5868a Mon Sep 17 00:00:00 2001 From: Kristjan Komlosi Date: Sun, 28 Dec 2025 16:40:00 +0100 Subject: [PATCH] handler: move mqttping into handler package; clean up main.go --- cmd/server/main.go | 15 ++------------- internal/handler/mqttping.go | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 13 deletions(-) create mode 100644 internal/handler/mqttping.go diff --git a/cmd/server/main.go b/cmd/server/main.go index f39d01f..08f74f0 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -74,19 +74,8 @@ func main() { r.GET("/hello", handler.Hello) r.POST("/login", handler.Login) - // mqttping endpoint: publish current timestamp to MQTT topic - r.POST("/mqttping", func(c *gin.Context) { - ts := time.Now().Format(time.RFC3339) - if mq == nil { - c.JSON(http.StatusServiceUnavailable, gin.H{"error": "mqtt not connected"}) - return - } - if err := mq.Publish(cfg.MQTT.Topic, []byte(ts)); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - c.JSON(http.StatusOK, gin.H{"timestamp": ts}) - }) + // mqttping endpoint handled by internal/handler + r.POST("/mqttping", handler.MQTTPing) // Protected routes auth := r.Group("/") diff --git a/internal/handler/mqttping.go b/internal/handler/mqttping.go new file mode 100644 index 0000000..89f2b2b --- /dev/null +++ b/internal/handler/mqttping.go @@ -0,0 +1,24 @@ +package handler + +import ( + "net/http" + "os" + "time" + + "github.com/gin-gonic/gin" + "git.piskot.si/SeminarM2/lambdaiot-core/internal/mqtt" +) + +// MQTTPing publishes the current timestamp to the configured MQTT topic +func MQTTPing(c *gin.Context) { + ts := time.Now().Format(time.RFC3339) + topic := os.Getenv("MQTT_TOPIC") + if topic == "" { + topic = "lambdaiot" + } + if err := mqtt.PublishDefault(topic, []byte(ts)); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"timestamp": ts}) +}