package main import ( "encoding/json" "fmt" "io" "log" "net/http" "gittea.marcokittel.de/elio/eliotools/datawriter/internal/database" ) type Container struct { Products map[string]int `json:"products"` Context Context `json:"context"` } type Product struct { Warehouse string `json:"warehouse"` Quantity int `json:"quantity"` Delivery int `json:"delivery_time"` } type OutgoingProducts struct { Products map[string][]Product `json:"products"` } func NewOutgoingProducts() *OutgoingProducts { op := OutgoingProducts{ Products: make(map[string][]Product), } return &op } type Context struct { Country string `json:"country"` State string `json:"state"` } const ( connectionString = "root:eliogeheim@tcp(127.0.0.1:3306)/elio_test?parseTime=true" ) func main() { //Env Variablen nutzen dbr := database.NewDatabaseReader(connectionString) http.HandleFunc("/api/products", func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { return } defer r.Body.Close() data, err := io.ReadAll(r.Body) if err != nil { log.Println(err) return } var foo Container err = json.Unmarshal(data, &foo) if err != nil { log.Println(err) return } fmt.Println(foo) result := []OutgoingProducts{} for key, item := range foo.Products { //Checken ob die Felder leer sind / Validitätsprüfung einbauen products, err := dbr.GetProductByProductIdDeliveryCountryAndState(key, foo.Context.Country, foo.Context.State) if err != nil { log.Println(err) } if len(products) == 0 { continue } gebrauchteProduktAnzahl := item op := NewOutgoingProducts() for _, db_products := range products { if gebrauchteProduktAnzahl <= 0 { continue } if db_products.Amount >= gebrauchteProduktAnzahl { newProduct := Product{Delivery: db_products.DeliveryDays, Quantity: gebrauchteProduktAnzahl, Warehouse: db_products.Warehouse} gebrauchteProduktAnzahl = 0 op.Products[key] = append(op.Products[key], newProduct) } else if db_products.Amount < gebrauchteProduktAnzahl { newProduct := Product{Delivery: db_products.DeliveryDays, Quantity: db_products.Amount, Warehouse: db_products.Warehouse} gebrauchteProduktAnzahl -= db_products.Amount op.Products[key] = append(op.Products[key], newProduct) } } result = append(result, *op) fmt.Println(op) } jsonResult, err := json.Marshal(result) if err != nil { log.Println(err) } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) fmt.Fprintln(w, string(jsonResult)) }) log.Fatal(http.ListenAndServe(":8080", nil)) }