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

add HTTP endpoint for creating new instances

parent 264a39a6
No related branches found
No related tags found
1 merge request!3Implement API server for DB inserts
Pipeline #54591 passed
package server
import (
"encoding/json"
"net/http"
"os"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"jonasled.dev/jonasled/ems-esp-logger/database"
"jonasled.dev/jonasled/ems-esp-logger/database/tables"
"jonasled.dev/jonasled/ems-esp-logger/log"
)
func initCreateInstanceRoute() {
apiKey := os.Getenv("MASTER_APIKEY")
if apiKey == "" {
log.Log.Fatal("MASTER_APIKEY is not specified")
}
R.POST("/api/instance", func(c *gin.Context) {
authHeader := c.GetHeader("Authentication")
if authHeader != 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 instance tables.Instance
body, _ := c.GetRawData()
err := json.Unmarshal(body, &instance)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed decoding json", "message": err.Error()})
return
}
if instance.Name == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "the name cannot be empty"})
return
}
var existingInstance tables.Instance
err = database.Db.Where("name = ?", instance.Name).First(&existingInstance).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
if err := database.Db.Create(&instance).Error; err != nil {
log.Log.Error("Failed to create instance: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed creating new instance definition"})
}
c.JSON(http.StatusCreated, gin.H{"message": "Created new entry"})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed creating new instance definition"})
log.Log.Error("Failed to query database, while trying to create new instance: %v", err)
}
} else {
existingInstance.Description = instance.Description
if err := database.Db.Save(&existingInstance).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed updating instance definition"})
log.Log.Error("Failed to query database, while trying to update instance: %v", err)
}
c.JSON(http.StatusCreated, gin.H{"message": "Updated entry"})
}
})
}
...@@ -14,6 +14,7 @@ func Init() { ...@@ -14,6 +14,7 @@ func Init() {
R.Use(ginlogrus.Logger(log.Log), gin.Recovery()) R.Use(ginlogrus.Logger(log.Log), gin.Recovery())
initGeneralRoutes() initGeneralRoutes()
initCreateInstanceRoute()
} }
func Run() { func Run() {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment