NewGit
Sign in
cart.go 45 lines852 B
 1package main
 2
 3import (
 4	"encoding/json"
 5	"net/http"
 6	"sync"
 7)
 8
 9type item struct {
10	ProductID int `json:"product_id"`
11	Quantity  int `json:"quantity"`
12}
13
14var (
15	mu   sync.Mutex
16	cart []item
17)
18
19func addToCart(w http.ResponseWriter, r *http.Request) {
20	var it item
21	if err := json.NewDecoder(r.Body).Decode(&it); err != nil {
22		http.Error(w, "bad JSON", http.StatusBadRequest)
23		return
24	}
25	mu.Lock()
26	cart = append(cart, it)
27	mu.Unlock()
28	w.WriteHeader(http.StatusCreated)
29}
30
31func showCart(w http.ResponseWriter, r *http.Request) {
32	mu.Lock()
33	defer mu.Unlock()
34	total := 0.0
35	for _, it := range cart {
36		for _, p := range products {
37			if p.ID == it.ProductID {
38				total += p.Price * float64(it.Quantity)
39			}
40		}
41	}
42	json.NewEncoder(w).Encode(map[string]any{"items": cart, "total": total})
43}
44
45func validQuantity(q int) bool { return q > 0 && q <= 99 }