91 lines
2.0 KiB
Go
91 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
|
|
"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"`
|
|
}
|
|
|
|
var (
|
|
connectionString = ""
|
|
port = ":8080"
|
|
)
|
|
|
|
const (
|
|
curlhelp = `curl -X POST localhost:8080/api/products -d '{ "products": { "A6053": 2, "B3009": 1200 }, "context": { "country": "EU", "state": "" } }'`
|
|
)
|
|
|
|
func main() {
|
|
connectionString := os.Getenv("CONNECTIONSTRING")
|
|
nps := database.NewProductService(connectionString)
|
|
if len(connectionString) == 0 {
|
|
fmt.Println("Connectionstring fehlt!. Bsp.: <user>:<passwort>@tcp(127.0.0.1:3306)/elio?parseTime=true")
|
|
return
|
|
}
|
|
//Env Variablen nutzen
|
|
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 payload database.Container
|
|
err = json.Unmarshal(data, &payload)
|
|
if err != nil {
|
|
log.Printf("Could not parse Json: %s", err)
|
|
return
|
|
}
|
|
result, err := nps.FetchData(&payload)
|
|
if err != nil {
|
|
//Todo Fehlerhandling
|
|
log.Println(err)
|
|
}
|
|
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.Printf("Easy Peasy: Die Party startet auf Port %s\n", port)
|
|
log.Printf("Probiers mal damit: %s\n", curlhelp)
|
|
log.Fatal(http.ListenAndServe(port, nil))
|
|
}
|