package main import ( "encoding/json" "net/http" "sync" ) type item struct { ProductID int `json:"product_id"` Quantity int `json:"quantity"` } var ( mu sync.Mutex cart []item ) func addToCart(w http.ResponseWriter, r *http.Request) { var it item if err := json.NewDecoder(r.Body).Decode(&it); err != nil { http.Error(w, "bad JSON", http.StatusBadRequest) return } mu.Lock() cart = append(cart, it) mu.Unlock() w.WriteHeader(http.StatusCreated) } func showCart(w http.ResponseWriter, r *http.Request) { mu.Lock() defer mu.Unlock() total := 0.0 for _, it := range cart { for _, p := range products { if p.ID == it.ProductID { total += p.Price * float64(it.Quantity) } } } json.NewEncoder(w).Encode(map[string]any{"items": cart, "total": total}) } func validQuantity(q int) bool { return q > 0 && q <= 99 }