Skip to content
Snippets Groups Projects
Commit 244e9e5c authored by Jonas Leder's avatar Jonas Leder
Browse files

add API endpoint for data upload

parent c8574eb1
Branches
No related tags found
Loading
Checking pipeline status
......@@ -15,6 +15,7 @@ func Init() {
initGeneralRoutes()
initCreateInstanceRoute()
initUploadDataRouter()
}
func Run() {
......
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"})
})
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment