diff --git a/server/main.go b/server/main.go index be39cf11ed593c9d61af4af3f85e48cc5557142d..5a3ada79d087f1b2c858f2a8320f8a2ce5b01f53 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 0000000000000000000000000000000000000000..b9a7137c57abb3cb57b6d6423c30ea530037a4ac --- /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"}) + }) +}