From 244e9e5ce7f80ce9303ccc84ec82cb787d6b5fa4 Mon Sep 17 00:00:00 2001 From: Jonas Leder <jonas@jonasled.de> Date: Sun, 26 Jan 2025 17:12:40 +0100 Subject: [PATCH] add API endpoint for data upload --- server/main.go | 1 + server/uploadDataRoute.go | 61 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 server/uploadDataRoute.go diff --git a/server/main.go b/server/main.go index be39cf1..5a3ada7 100644 --- a/server/main.go +++ b/server/main.go @@ -15,6 +15,7 @@ func Init() { initGeneralRoutes() initCreateInstanceRoute() + initUploadDataRouter() } func Run() { diff --git a/server/uploadDataRoute.go b/server/uploadDataRoute.go new file mode 100644 index 0000000..b9a7137 --- /dev/null +++ b/server/uploadDataRoute.go @@ -0,0 +1,61 @@ +package server + +import ( + "encoding/json" + "net/http" + + "github.com/gin-gonic/gin" + "jonasled.dev/jonasled/ems-esp-logger/database" + "jonasled.dev/jonasled/ems-esp-logger/database/tables" + "jonasled.dev/jonasled/ems-esp-logger/queue" + "jonasled.dev/jonasled/ems-esp-logger/types" +) + +func initUploadDataRouter() { + R.POST("/api/data", func(c *gin.Context) { + instanceHeader := c.GetHeader("X-Instance") + if instanceHeader == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Missing X-Instance header"}) + return + } + var instance tables.Instance + err := database.Db.Where("name = ?", instanceHeader).First(&instance).Error + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "No matching instance found"}) + return + } + + authHeader := c.GetHeader("Authentication") + if authHeader != instance.Apikey { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + contentType := c.GetHeader("Content-Type") + if contentType == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Content-Type header missing"}) + return + } + if contentType != "application/json" { + c.JSON(http.StatusBadRequest, gin.H{"error": "expected application/json as content type"}) + return + } + + var uploadedTask types.Task + body, _ := c.GetRawData() + err = json.Unmarshal(body, &uploadedTask) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "failed decoding json", "message": err.Error()}) + return + } + if uploadedTask.Data == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "the data field cannot be empty"}) + return + } + if uploadedTask.Instance == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "the instance field cannot be empty"}) + return + } + queue.MainQueue.Enqueue(string(body), 0) + c.JSON(http.StatusOK, gin.H{"message": "Accepted new data"}) + }) +} -- GitLab